repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-filters.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) param_filt=(gabor gaussian median rank_order unsharp_mask sobel prewitt scharr roberts roberts_pos_diag roberts_neg_diag farid laplace meijering sato frangi hessian threshold_isodata threshold_otsu threshold_yen threshold_local threshold_li threshold_minimum threshold_mean threshold_triangle threshold_niblack threshold_sauvola apply_hysteresis_threshold threshold_multiotsu) # param_filt=(rank_order ) param_dt=(float64 float32 float16) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_filters_bench.py -f $filt -i $shape -d $dt -t 10 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/_image_bench.py
import itertools import math import re import subprocess import time import types from collections import abc import cupy as cp import cupyx.scipy.ndimage import numpy as np import pandas as pd import scipy.ndimage import skimage.data from cucim.time import repeat def product_dict(**kwargs): # https://stackoverflow.com/questions/5228158/cartesian-product-of-a-dictionary-of-lists keys = kwargs.keys() vals = kwargs.values() for instance in itertools.product(*vals): yield dict(zip(keys, instance)) class ImageBench(object): def __init__( self, function_name, shape, dtypes=[np.float32], fixed_kwargs={}, var_kwargs={}, index_str=None, # extra string to append to dataframe index module_cpu=scipy.ndimage, module_gpu=cupyx.scipy.ndimage, function_is_generator=False, run_cpu=True, ): self.shape = shape self.function_name = function_name self.fixed_kwargs_cpu = self._update_kwargs_arrays(fixed_kwargs, "cpu") self.fixed_kwargs_gpu = self._update_kwargs_arrays(fixed_kwargs, "gpu") self.var_kwargs = var_kwargs self.index_str = index_str # self.set_args_kwargs = set_args_kwargs if not isinstance(dtypes, abc.Sequence): dtypes = [dtypes] self.dtypes = [np.dtype(d) for d in dtypes] if not function_is_generator: self.func_cpu = getattr(module_cpu, function_name) self.func_gpu = getattr(module_gpu, function_name) else: # benchmark by generating all values def gen_cpu(*args, **kwargs): generator = getattr(module_cpu, function_name)(*args, **kwargs) return list(generator) def gen_gpu(*args, **kwargs): generator = getattr(module_gpu, function_name)(*args, **kwargs) return list(generator) self.func_cpu = gen_cpu self.func_gpu = gen_gpu self.module_name_cpu = module_cpu.__name__ self.module_name_gpu = module_gpu.__name__ self.run_cpu = run_cpu def set_args(self, dtype): if np.dtype(dtype).kind in "iu": im1 = skimage.data.camera() im1 = im1.astype(dtype) else: im1 = skimage.data.camera() / 255.0 im1 = im1.astype(dtype) if len(self.shape) == 3: im1 = im1[..., np.newaxis] n_tile = [math.ceil(s / im_s) for s, im_s in zip(self.shape, im1.shape)] slices = tuple([slice(s) for s in self.shape]) image = np.tile(im1, n_tile)[slices] imaged = cp.asarray(image) assert imaged.dtype == dtype assert imaged.shape == self.shape self.args_cpu = (image,) self.args_gpu = (imaged,) def _update_array(self, array, target="cpu"): if target == "gpu" and isinstance(array, np.ndarray): array = cp.asarray(array) elif target == "cpu" and isinstance(array, cp.ndarray): array = cp.asnumpy(array) return array def _update_kwargs_arrays(self, kwargs, target="cpu"): new_dict = {} for k, v in kwargs.items(): new_dict[k] = self._update_array(v, target=target) return new_dict def _index(self, name, var_kwargs, dtype=None, shape=None): index = name if var_kwargs: index += " (" params = [] for k, v in var_kwargs.items(): if isinstance(v, types.FunctionType): params.append(f"{k}={v.__name__}") elif isinstance(v, (np.ndarray, cp.ndarray)): params.append(f"{k}=array,shape={v.shape},dtype={v.dtype.name}") else: params.append(f"{k}={v}") if dtype is not None: params.append(f", {np.dtype(dtype).name}") if shape is not None: params.append(f"s={shape}") index += ", ".join(params) index.replace(",,", ",") if var_kwargs: index += ") " if self.index_str is not None: index += ", " + self.index_str return index def get_reps(self, func, args, kwargs, target_duration=5, cpu=True): if not cpu: # dry run func(*args, **kwargs) # time 1 repetition d = cp.cuda.Device() tstart = time.time() func(*args, **kwargs) d.synchronize() dur = time.time() - tstart n_repeat = max(1, math.ceil(target_duration / dur)) if cpu: n_warmup = 0 else: n_warmup = max(1, math.ceil(n_repeat / 5)) reps = dict(n_warmup=n_warmup, n_repeat=n_repeat) return reps def run_benchmark(self, duration=3, verbose=True): df = pd.DataFrame() self.df = df kw_lists = self.var_kwargs pdict = list(product_dict(**kw_lists)) for dtype in self.dtypes: self.set_args(dtype) for i, var_kwargs1 in enumerate(pdict): # arr_index = indices[i] index = self._index(self.function_name, var_kwargs1) # transfer any arrays in kwargs to the appropriate device var_kwargs_cpu = self._update_kwargs_arrays(var_kwargs1, "cpu") var_kwargs_gpu = self._update_kwargs_arrays(var_kwargs1, "gpu") # Note: brute_force=True on 'gpu' because False is not # implemented if "brute_force" in var_kwargs_gpu: var_kwargs_gpu["brute_force"] = True kw_cpu = {**self.fixed_kwargs_cpu, **var_kwargs_cpu} kw_gpu = {**self.fixed_kwargs_gpu, **var_kwargs_gpu} rep_kwargs_cpu = self.get_reps( self.func_cpu, self.args_cpu, kw_cpu, duration, cpu=True ) rep_kwargs_gpu = self.get_reps( self.func_gpu, self.args_gpu, kw_gpu, duration, cpu=False ) print("Number of Repetitions : ", rep_kwargs_gpu) perf_gpu = repeat( self.func_gpu, self.args_gpu, kw_gpu, **rep_kwargs_gpu ) df.at[index, "shape"] = f"{self.shape}" # df.at[index, "description"] = index df.at[index, "function_name"] = self.function_name df.at[index, "dtype"] = np.dtype(dtype).name df.at[index, "ndim"] = len(self.shape) if self.run_cpu is True: perf = repeat( self.func_cpu, self.args_cpu, kw_cpu, **rep_kwargs_cpu ) df.at[index, "GPU accel"] = ( perf.cpu_times.mean() / perf_gpu.gpu_times.mean() ) df.at[index, "CPU: host (mean)"] = perf.cpu_times.mean() df.at[index, "CPU: host (std)"] = perf.cpu_times.std() df.at[index, "GPU: host (mean)"] = perf_gpu.cpu_times.mean() df.at[index, "GPU: host (std)"] = perf_gpu.cpu_times.std() df.at[index, "GPU: device (mean)"] = perf_gpu.gpu_times.mean() df.at[index, "GPU: device (std)"] = perf_gpu.gpu_times.std() with cp.cuda.Device() as device: props = cp.cuda.runtime.getDeviceProperties(device.id) gpu_name = props["name"].decode() df.at[index, "GPU: DEV Name"] = [ gpu_name for i in range(len(df)) ] cmd = "cat /proc/cpuinfo" cpuinfo = subprocess.check_output(cmd, shell=True).strip() cpu_name = ( re.search("\nmodel name.*\n", cpuinfo.decode()) .group(0) .strip("\n") ) cpu_name = cpu_name.replace("model name\t: ", "") df.at[index, "CPU: DEV Name"] = [ cpu_name for i in range(len(df)) ] # accelerations[arr_index] = df.at[index, "GPU accel"] if verbose: print(df.loc[index]) results = {} results["full"] = df results["var_kwargs_names"] = list(self.var_kwargs.keys()) results["var_kwargs_values"] = list(self.var_kwargs.values()) results["function_name"] = self.function_name results["module_name_cpu"] = self.module_name_cpu results["module_name_gpu"] = self.module_name_gpu return results
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-restoration.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) param_filt=(denoise_tv_chambolle calibrate_denoiser wiener unsupervised_wiener richardson_lucy) param_dt=(float32 uint8) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_restoration_bench.py -f $filt -i $shape -d $dt -t 10 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_segmentation_bench.py
import argparse import math import os import pickle import cupy as cp import numpy as np import pandas as pd import skimage import skimage.segmentation from _image_bench import ImageBench import cucim.skimage from cucim.skimage import data, measure class LabelBench(ImageBench): def __init__( self, function_name, shape, dtypes=np.float32, fixed_kwargs={}, var_kwargs={}, index_str=None, module_cpu=skimage.measure, module_gpu=cucim.skimage.measure, run_cpu=True, ): super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=module_cpu, module_gpu=module_gpu, run_cpu=run_cpu, ) def _generate_labels(self, dtype): ndim = len(self.shape) blobs_kwargs = dict( blob_size_fraction=0.05, volume_fraction=0.35, rng=5 ) # binary blobs only creates square outputs labels = measure.label( data.binary_blobs(max(self.shape), n_dim=ndim, **blobs_kwargs) ) print(f"# labels generated = {labels.max()}") # crop to rectangular labels = labels[tuple(slice(s) for s in self.shape)] return labels.astype(dtype, copy=False) def set_args(self, dtype): labels_d = self._generate_labels(dtype) labels = cp.asnumpy(labels_d) self.args_cpu = (labels,) self.args_gpu = (labels_d,) class LabelAndImageBench(LabelBench): def set_args(self, dtype): labels_d = self._generate_labels(dtype) labels = cp.asnumpy(labels_d) image_d = cp.random.standard_normal(labels.shape).astype(np.float32) image = cp.asnumpy(image_d) self.args_cpu = (image, labels) self.args_gpu = (image_d, labels_d) class MorphGeodesicBench(ImageBench): def set_args(self, dtype): if np.dtype(dtype).kind in "iu": im1 = skimage.data.camera() else: im1 = skimage.data.camera() / 255.0 im1 = im1.astype(dtype) if len(self.shape) == 3: im1 = im1[..., np.newaxis] im1 = cp.array(im1) n_tile = [math.ceil(s / im_s) for s, im_s in zip(self.shape, im1.shape)] slices = tuple([slice(s) for s in self.shape]) imaged = cp.tile(im1, n_tile)[slices] # need this preprocessing for morphological_geodesic_active_contour imaged = cp.array( skimage.segmentation.inverse_gaussian_gradient(cp.asnumpy(imaged)) ) image = cp.asnumpy(imaged) assert imaged.dtype == dtype assert imaged.shape == self.shape self.args_cpu = (image,) self.args_gpu = (imaged,) class RandomWalkerBench(ImageBench): def set_args(self, dtype): # Note: dtype only used for merkers array, data is hard-coded as float32 if np.dtype(dtype).kind not in "iu": raise ValueError("random_walker markers require integer dtype") n_dim = len(self.shape) data = cucim.skimage.img_as_float( cucim.skimage.data.binary_blobs( length=max(self.shape), n_dim=n_dim, rng=1 ) ) data = data[tuple(slice(s) for s in self.shape)] sigma = 0.35 rng = np.random.default_rng(5) data += cp.array(rng.normal(loc=0, scale=sigma, size=data.shape)) data = cucim.skimage.exposure.rescale_intensity( data, in_range=(-sigma, 1 + sigma), out_range=(-1, 1) ) data = data.astype(cp.float32) data_cpu = cp.asnumpy(data) # The range of the binary image spans over (-1, 1). # We choose the hottest and the coldest pixels as markers. markers = cp.zeros(data.shape, dtype=dtype) markers[data < -0.95] = 1 markers[data > 0.95] = 2 markers_cpu = cp.asnumpy(markers) self.args_cpu = (data_cpu, markers_cpu) self.args_gpu = (data, markers) def main(args): pfile = "cucim_segmentation_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] dtypes_label = [np.dtype(args.dtype_label)] # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) run_cpu = not args.no_cpu for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ # _clear_border.py ( "clear_border", dict(), dict(), False, True, ), # _expand_labels.py ( "expand_labels", dict(distance=1), dict(), False, True, ), # _join.py ( "relabel_sequential", dict(offset=5), dict(), False, True, ), # boundaries.py ( "find_boundaries", dict(), dict( connectivity=[1], mode=["thick", "inner", "outer", "subpixel"] ), False, True, ), ( "mark_boundaries", dict(), dict(), False, True, ), ( "random_walker", dict(beta=4, tol=1.0e-4, prob_tol=1.0e-2), dict(mode=["cg", "cg_j"]), False, True, ), # morphsnakes.py ("inverse_gaussian_gradient", dict(), dict(), False, True), ( "morphological_geodesic_active_contour", dict(), dict(num_iter=[16], init_level_set=["checkerboard", "disk"]), False, False, ), ( "morphological_chan_vese", dict(), dict(num_iter=[16], init_level_set=["checkerboard", "disk"]), False, False, ), ( "chan_vese", dict(), # Reduced number of iterations so scikit-image comparison will not # take minutes to complete. Empirically, approximately the same # acceleration was measured for 10 or 100 iterations. dict(max_num_iter=[10], init_level_set=["checkerboard", "disk"]), False, False, ), # omit: disk_level_set (simple array generation function) # omit: checkerboard_level_set (simple array generation function) ]: if function_name != args.func_name: continue ndim = len(shape) if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue if function_name in [ "clear_border", "expand_labels", "relabel_sequential", "find_boundaries", "mark_boundaries", "random_walker", ]: if function_name == "random_walker": fixed_kwargs["channel_axis"] = -1 if shape[-1] == 3 else None if function_name == "mark_boundaries": bench_func = LabelAndImageBench elif function_name == "random_walker": bench_func = RandomWalkerBench else: bench_func = LabelBench B = bench_func( function_name=function_name, shape=shape, dtypes=dtypes_label, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.segmentation, module_gpu=cucim.skimage.segmentation, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) elif function_name in [ "inverse_gaussian_gradient", "morphological_geodesic_active_contour", "morphological_chan_vese", "chan_vese", ]: if function_name == "morphological_geodesic_active_contour": bench_class = MorphGeodesicBench else: bench_class = ImageBench B = bench_class( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.segmentation, module_gpu=cucim.skimage.segmentation, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) try: import tabular # noqa: F401 with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) except ImportError: pass if __name__ == "__main__": parser = argparse.ArgumentParser( description="Benchmarking cuCIM segmentation functions" ) func_name_choices = [ "clear_border", "expand_labels", "relabel_sequential", "find_boundaries", "mark_boundaries", "random_walker", "inverse_gaussian_gradient", "morphological_geodesic_active_contour", "morphological_chan_vese", "chan_vese", ] label_dtype_choices = [ "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help=( "Size of input image (omit color channel, it will be appended " "as needed)" ), required=True, ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "--dtype_label", type=str, help="Dtype of input image", choices=label_dtype_choices, required=False, default="uint8", ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-feature.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) param_filt=(multiscale_basic_features canny daisy structure_tensor hessian_matrix hessian_matrix_det shape_index corner_kitchen_rosenfeld corner_harris corner_shi_tomasi corner_foerstner corner_peaks match_template blob_dog blob_log blob_doh) param_dt=(float64 float32) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_feature_bench.py -f $filt -i $shape -d $dt -t 3 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_feature_bench.py
import argparse import math import os import pickle import cupy as cp import numpy as np import pandas as pd import skimage import skimage.feature from _image_bench import ImageBench from skimage import data, draw import cucim.skimage import cucim.skimage.feature from cucim.skimage import exposure class BlobDetectionBench(ImageBench): def set_args(self, dtype): ndim = len(self.shape) if ndim == 2: # create 2D image by tiling the coins image img = cp.array(data.coins()) img = exposure.equalize_hist(img) # improves detection n_tile = (math.ceil(s / s0) for s, s0 in zip(self.shape, img.shape)) img = cp.tile(img, n_tile) img = img[tuple(slice(s) for s in img.shape)] img = img.astype(dtype, copy=False) elif ndim == 3: # create 3D volume with randomly positioned ellipses e = cp.array(draw.ellipsoid(*(max(s // 20, 1) for s in self.shape))) e = e.astype(dtype, copy=False) img = cp.zeros(self.shape, dtype=dtype) rng = np.random.default_rng(5) num_ellipse = 64 offsets = rng.integers(0, np.prod(img.shape), num_ellipse) locs = np.unravel_index(offsets, img.shape) for loc in zip(*locs): loc = tuple( min(p, s - es) for p, s, es in zip(loc, img.shape, e.shape) ) sl = tuple(slice(p, p + es) for p, es in zip(loc, e.shape)) img[sl] = e else: raise NotImplementedError("unsupported ndim") self.args_gpu = (img,) self.args_cpu = (cp.asnumpy(img),) class MatchTemplateBench(ImageBench): def set_args(self, dtype): rstate = cp.random.RandomState(5) imaged = rstate.standard_normal(self.shape) > 2 imaged = imaged.astype(dtype) templated = cp.zeros((3,) * imaged.ndim, dtype=dtype) templated[(1,) * imaged.ndim] = 1 image = cp.asnumpy(imaged) template = cp.asnumpy(templated) assert imaged.dtype == dtype assert imaged.shape == self.shape self.args_cpu = (image, template) self.args_gpu = (imaged, templated) def main(args): pfile = "cucim_feature_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ ( "multiscale_basic_features", dict(edges=True), dict(texture=[True, False]), True, True, ), ("canny", dict(sigma=1.8), dict(), False, False), # reduced default rings, histograms, orientations to fit daisy at # (3840, 2160) into GPU memory ( "daisy", dict(step=4, radius=15, rings=2, histograms=5, orientations=4), dict(normalization=["l1", "l2", "daisy"]), False, False, ), ( "structure_tensor", dict(sigma=1, mode="reflect", order="rc"), dict(), False, True, ), ( "hessian_matrix", dict(sigma=1, mode="reflect", order="rc"), dict(), False, True, ), ( "hessian_matrix_det", dict(sigma=1, approximate=False), dict(), False, True, ), ("shape_index", dict(sigma=1, mode="reflect"), dict(), False, False), ( "corner_kitchen_rosenfeld", dict(mode="reflect"), dict(), False, False, ), ( "corner_harris", dict(k=0.05, eps=1e-6, sigma=1), dict(method=["k", "eps"]), False, False, ), ("corner_shi_tomasi", dict(sigma=1), dict(), False, False), ("corner_foerstner", dict(sigma=1), dict(), False, False), ("corner_peaks", dict(), dict(min_distance=(2, 3, 5)), False, True), ( "match_template", dict(), dict(pad_input=[False], mode=["reflect"]), False, True, ), # blob detectors, fixed kwargs are taken from the docstring examples ( "blob_dog", dict(threshold=0.05, min_sigma=10, max_sigma=40), dict(), False, True, ), ("blob_log", dict(threshold=0.3), dict(), False, True), ("blob_doh", dict(), dict(), False, False), ]: if function_name == args.func_name: shape = tuple(list(map(int, (args.img_size.split(","))))) else: continue ndim = len(shape) run_cpu = not args.no_cpu if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue if function_name.startswith("blob"): if ndim == 3: # set more reasonable threshold for the synthetic 3d data if function_name == "blob_log": fixed_kwargs = {"threshold": 0.6} else: fixed_kwargs = {} B = BlobDetectionBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.feature, module_gpu=cucim.skimage.feature, run_cpu=run_cpu, ) elif function_name != "match_template": if function_name == "multiscale_basic_features": fixed_kwargs["channel_axis"] = -1 if shape[-1] == 3 else None if ndim == 3 and shape[-1] != 3: # Omit texture=True case to avoid excessive GPU memory usage var_kwargs["texture"] = [False] B = ImageBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.feature, module_gpu=cucim.skimage.feature, run_cpu=run_cpu, ) else: B = MatchTemplateBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.feature, module_gpu=cucim.skimage.feature, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Benchmarking cuCIM Feature") # fmt: off func_name_choices = [ "multiscale_basic_features", "canny", "daisy", "structure_tensor", "hessian_matrix", "hessian_matrix_det", "shape_index", "corner_kitchen_rosenfeld", "corner_harris", "corner_shi_tomasi", "corner_foerstner", "corner_peaks", "match_template", "blob_dog", "blob_log", "blob_doh", ] dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64" ] parser.add_argument( "-i", "--img_size", type=str, help="Size of input image", required=True ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False ) # fmt: on args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cupyx_scipy_ndimage_morphology_bench.py
import os import pickle import cupy as cp import cupyx.scipy.ndimage import numpy as np import pandas as pd import scipy import scipy.ndimage as ndi from _image_bench import ImageBench class BinaryMorphologyBench(ImageBench): def __init__( self, function_name, shape, structure=None, mask=None, dtypes=[np.float32], fixed_kwargs={}, var_kwargs={}, index_str="", module_cpu=scipy.ndimage, module_gpu=cupyx.scipy.ndimage, ): array_kwargs = dict(structure=structure, mask=mask) if "structure" in fixed_kwargs: raise ValueError("fixed_kwargs cannot contain 'structure'") if "mask" in fixed_kwargs: raise ValueError("fixed_kwargs cannot contain 'mask'") fixed_kwargs.update(array_kwargs) super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, index_str=index_str, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=module_cpu, module_gpu=module_gpu, ) def set_args(self, dtype): imaged = cp.random.standard_normal(self.shape).astype(dtype) > 0 image = cp.asnumpy(imaged) self.args_cpu = (image,) self.args_gpu = (imaged,) class MorphologyBench(ImageBench): def __init__( self, function_name, shape, structure=None, footprint=None, dtypes=[np.float32], fixed_kwargs={}, var_kwargs={}, module_cpu=scipy.ndimage, module_gpu=cupyx.scipy.ndimage, ): array_kwargs = dict(structure=structure, footprint=footprint) if "structure" in fixed_kwargs: raise ValueError("fixed_kwargs cannot contain 'structure'") if "footprint" in fixed_kwargs: raise ValueError("fixed_kwargs cannot contain 'footprint'") fixed_kwargs.update(array_kwargs) super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=module_cpu, module_gpu=module_gpu, ) def set_args(self, dtype): imaged = cp.random.standard_normal(self.shape).astype(dtype) image = cp.asnumpy(imaged) self.args_cpu = (image,) self.args_gpu = (imaged,) pfile = "morphology_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() modes = ["reflect"] sizes = [3, 5, 7, 9] dtypes = [np.float32] for shape in [(512, 512), (3840, 2160), (192, 192, 192)]: ndim = len(shape) for fname, var_kwargs in [ ("grey_erosion", dict(mode=modes, size=sizes)), ("grey_dilation", dict(mode=modes, size=sizes)), ("grey_opening", dict(mode=modes, size=sizes)), ("grey_closing", dict(mode=modes, size=sizes)), ("morphological_gradient", dict(mode=modes, size=sizes)), ("morphological_laplace", dict(mode=modes, size=sizes)), ("white_tophat", dict(mode=modes, size=sizes)), ("black_tophat", dict(mode=modes, size=sizes)), ]: B = MorphologyBench( function_name=fname, shape=shape, dtypes=dtypes, structure=None, footprint=None, # Note: Benchmark runner will change brute_force to True for the GPU fixed_kwargs=dict(output=None), var_kwargs=var_kwargs, ) results = B.run_benchmark(duration=1) all_results = pd.concat([all_results, results["full"]]) iterations = [1, 10, 30] for fname, var_kwargs in [ ("binary_erosion", dict(iterations=iterations, brute_force=[False])), ("binary_dilation", dict(iterations=iterations, brute_force=[False])), ("binary_opening", dict(iterations=iterations, brute_force=[False])), ("binary_closing", dict(iterations=iterations, brute_force=[False])), ("binary_propagation", dict()), ]: for connectivity in range(1, ndim + 1): index_str = f"conn={connectivity}" structure = ndi.generate_binary_structure(ndim, connectivity) B = BinaryMorphologyBench( function_name=fname, shape=shape, dtypes=dtypes, structure=structure, mask=None, index_str=index_str, # Note: Benchmark runner will change brute_force to True for the GPU # noqa: E501 fixed_kwargs=dict(output=None), var_kwargs=var_kwargs, ) results = B.run_benchmark(duration=1) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown())
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/bench_convolve.py
""" Benchmark locally modified ndimage functions vs. their CuPy counterparts """ import cupy as cp import cupyx.scipy.ndimage as ndi from cupyx.profiler import benchmark from cucim.skimage._vendored.ndimage import ( # noqa: F401 convolve1d, correlate1d, gaussian_filter, gaussian_filter1d, gaussian_gradient_magnitude, gaussian_laplace, laplace, prewitt, sobel, uniform_filter, uniform_filter1d, ) d = cp.cuda.Device() def _get_image(shape, dtype, seed=123): rng = cp.random.default_rng(seed) dtype = cp.dtype(dtype) if dtype.kind == "b": image = rng.integers(0, 1, shape, dtype=cp.uint8).astype(bool) elif dtype.kind in "iu": image = rng.integers(0, 128, shape, dtype=dtype) elif dtype.kind in "c": real_dtype = cp.asarray([], dtype=dtype).real.dtype image = rng.standard_normal(shape, dtype=real_dtype) image = image + 1j * rng.standard_normal(shape, dtype=real_dtype) else: if dtype == cp.float16: image = rng.standard_normal(shape).astype(dtype) else: image = rng.standard_normal(shape, dtype=dtype) return image def _compare_implementations( shape, kernel_size, axis, dtype, mode, cval=0.0, origin=0, output_dtype=None, kernel_dtype=None, output_preallocated=False, function=convolve1d, max_duration=1, ): dtype = cp.dtype(dtype) if kernel_dtype is None: kernel_dtype = dtype image = _get_image(shape, dtype) kernel = _get_image((kernel_size,), kernel_dtype) kwargs = dict(axis=axis, mode=mode, cval=cval, origin=origin) if output_dtype is not None: output_dtype = cp.dtype(output_dtype) function_ref = getattr(ndi, function.__name__) if output_preallocated: if output_dtype is None: output_dtype = image.dtype output1 = cp.empty(image.shape, dtype=output_dtype) output2 = cp.empty(image.shape, dtype=output_dtype) kwargs.update(dict(output=output1)) perf1 = benchmark( function_ref, (image, kernel), kwargs=kwargs, n_warmup=10, n_repeat=10000, max_duration=max_duration, ) kwargs.update(dict(output=output2, algorithm="shared_memory")) perf2 = benchmark( function, (image, kernel), kwargs=kwargs, n_warmup=10, n_repeat=10000, max_duration=max_duration, ) return perf1, perf2 kwargs.update(dict(output=output_dtype)) perf1 = benchmark( function_ref, (image, kernel), kwargs=kwargs, n_warmup=10, n_repeat=10000, max_duration=max_duration, ) kwargs.update(dict(output=output_dtype, algorithm="shared_memory")) perf2 = benchmark( function, (image, kernel), kwargs=kwargs, n_warmup=10, n_repeat=10000, max_duration=max_duration, ) return perf1, perf2 def _compare_implementations_other( shape, dtype, mode, cval=0.0, output_dtype=None, kernel_dtype=None, output_preallocated=False, function=convolve1d, func_kwargs={}, max_duration=1, ): dtype = cp.dtype(dtype) image = _get_image(shape, dtype) kwargs = dict(mode=mode, cval=cval) if func_kwargs: kwargs.update(func_kwargs) if output_dtype is not None: output_dtype = cp.dtype(output_dtype) function_ref = getattr(ndi, function.__name__) if output_preallocated: if output_dtype is None: output_dtype = image.dtype output1 = cp.empty(image.shape, dtype=output_dtype) kwargs.update(dict(output=output1)) perf1 = benchmark( function_ref, (image,), kwargs=kwargs, n_warmup=10, n_repeat=10000, max_duration=max_duration, ) kwargs.update(dict(output=output1, algorithm="shared_memory")) perf2 = benchmark( function, (image,), kwargs=kwargs, n_warmup=10, n_repeat=10000, max_duration=max_duration, ) return perf1, perf2 kwargs.update(dict(output=output_dtype)) perf1 = benchmark( function_ref, (image,), kwargs=kwargs, n_warmup=10, n_repeat=10000, max_duration=max_duration, ) kwargs.update(dict(output=output_dtype, algorithm="shared_memory")) perf2 = benchmark( function, (image,), kwargs=kwargs, n_warmup=10, n_repeat=10000, max_duration=max_duration, ) return perf1, perf2 print("\n\n") print( "function | shape | dtype | mode | kernel size | preallocated | axis | dur (ms), CuPy | dur (ms), cuCIM | acceleration " # noqa: E501 ) print( "---------|-------|-------|------|-------------|--------------|------|----------------|-----------------|--------------" # noqa: E501 ) for function in [convolve1d]: for shape in [(512, 512), (3840, 2160), (64, 64, 64), (256, 256, 256)]: for dtype in [cp.float32, cp.uint8]: for mode in ["nearest"]: for kernel_size in [3, 7, 11, 41]: for output_preallocated in [False]: # , True]: for axis in range(len(shape)): output_dtype = dtype perf1, perf2 = _compare_implementations( shape=shape, kernel_size=kernel_size, mode=mode, axis=axis, dtype=dtype, output_dtype=output_dtype, output_preallocated=output_preallocated, function=function, ) t_elem = perf1.gpu_times * 1000.0 t_shared = perf2.gpu_times * 1000.0 print( f"{function.__name__} | {shape} | {cp.dtype(dtype).name} | {mode} | {kernel_size=} | prealloc={output_preallocated} | {axis=} | {t_elem.mean():0.3f} +/- {t_elem.std():0.3f} | {t_shared.mean():0.3f} +/- {t_shared.std():0.3f} | {t_elem.mean() / t_shared.mean():0.3f}" # noqa: E501 ) print( "function | kwargs | shape | dtype | mode | preallocated | dur (ms), CuPy | dur (ms), cuCIM | acceleration " # noqa: E501 ) print( "---------|--------|-------|-------|------|--------------|----------------|-----------------|--------------" # noqa: E501 ) for function, func_kwargs in [ # (gaussian_filter1d, dict(sigma=1.0, axis=0)), # (gaussian_filter1d, dict(sigma=1.0, axis=-1)), # (gaussian_filter1d, dict(sigma=4.0, axis=0)), # (gaussian_filter1d, dict(sigma=4.0, axis=-1)), (gaussian_filter, dict(sigma=1.0)), (gaussian_filter, dict(sigma=4.0)), (uniform_filter, dict(size=11)), (prewitt, dict(axis=0)), (sobel, dict(axis=0)), (prewitt, dict(axis=-1)), (sobel, dict(axis=-1)), ]: for shape in [(512, 512), (3840, 2160), (64, 64, 64), (256, 256, 256)]: for dtype, output_dtype in [ (cp.float32, cp.float32), (cp.uint8, cp.float32), ]: for mode in ["nearest"]: for output_preallocated in [False, True]: perf1, perf2 = _compare_implementations_other( shape=shape, mode=mode, dtype=dtype, output_dtype=output_dtype, output_preallocated=output_preallocated, function=function, func_kwargs=func_kwargs, ) t_elem = perf1.gpu_times * 1000.0 t_shared = perf2.gpu_times * 1000.0 print( f"{function.__name__} | {func_kwargs} | {shape} | {cp.dtype(dtype).name} | {mode} | {output_preallocated} | {t_elem.mean():0.3f} +/- {t_elem.std():0.3f} | {t_shared.mean():0.3f} +/- {t_shared.std():0.3f} | {t_elem.mean() / t_shared.mean():0.3f}" # noqa: E501 )
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_transform_bench.py
import argparse import os import pickle import numpy as np import pandas as pd import skimage import skimage.transform from _image_bench import ImageBench import cucim.skimage import cucim.skimage.transform def main(args): pfile = "cucim_transform_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) run_cpu = not args.no_cpu for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ # _warps.py ( "resize", dict(preserve_range=True), dict(order=[0, 1, 3], mode=["reflect"], anti_aliasing=[True]), True, True, ), # scale handled in loop below ( "resize_local_mean", dict(preserve_range=True), {}, True, True, ), # scale handled in loop below ( "rescale", dict(preserve_range=True), dict(order=[0, 1, 3], mode=["reflect"], anti_aliasing=[True]), True, True, ), # output_shape handled in loop below ( "rotate", dict(angle=15, preserve_range=True), dict(order=[0, 1, 3], mode=["reflect"], resize=[False, True]), False, False, ), ( "downscale_local_mean", dict(), dict(), True, True, ), # factors handled in loop below ( "swirl", dict(strength=1, preserve_range=True), dict(order=[0, 1, 3], mode=["reflect"]), False, False, ), # TODO : warp? already indirectly benchmarked via swirl, etc ("warp_polar", dict(), dict(scaling=["linear", "log"]), True, False), # integral.py ("integral_image", dict(), dict(), False, True), # TODO: integrate # pyramids.py ( "pyramid_gaussian", dict(max_layer=6, downscale=2, preserve_range=True), dict(order=[0, 1, 3]), True, True, ), ( "pyramid_laplacian", dict(max_layer=6, downscale=2, preserve_range=True), dict(order=[0, 1, 3]), True, True, ), ]: if function_name != args.func_name: continue ndim = len(shape) if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue ndim_spatial = ndim - 1 if shape[-1] == 3 else ndim if function_name in [ "rescale", "warp_polar", "pyramid_gaussian", "pyramid_laplacian", ]: fixed_kwargs["channel_axis"] = -1 if ndim_spatial < ndim else None function_is_generator = function_name in [ "pyramid_gaussian", "pyramid_laplacian", ] if function_name in ["rescale", "resize", "resize_local_mean"]: scales = [0.75, 1.25] if function_name == "rescale": var_kwargs["scale"] = [(s,) * ndim_spatial for s in scales] elif function_name.startswith("resize"): out_shapes = [[int(s_ * s) for s_ in shape] for s in scales] if ndim_spatial < ndim: # don't resize along channels dimension out_shapes = [ tuple([int(s_ * s) for s_ in shape[:-1]]) + (shape[-1],) for s in scales ] else: out_shapes = [ tuple([int(s_ * s) for s_ in shape]) for s in scales ] var_kwargs["output_shape"] = out_shapes elif function_name == "downscale_local_mean": if ndim_spatial < ndim: # no downscaling along channels axis factors = [(2,) * (ndim - 1) + (1,)] else: factors = [(2,) * (ndim - 1) + (4,)] var_kwargs["factors"] = factors B = ImageBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.transform, module_gpu=cucim.skimage.transform, function_is_generator=function_is_generator, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) try: import tabular # noqa: F401 with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) except ImportError: pass if __name__ == "__main__": parser = argparse.ArgumentParser( description="Benchmarking cuCIM transform functions" ) func_name_choices = [ "resize", "resize_local_mean", "rescale", "rotate", "downscale_local_mean", "warp_polar", "integral_image", "pyramid_gaussian", "pyramid_laplacian", ] dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help=( "Size of input image (omit color channel, it will be appended " "as needed)" ), required=True, ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_filters_bench.py
import argparse import os import pickle import numpy as np import pandas as pd import skimage import skimage.filters from _image_bench import ImageBench import cucim.skimage import cucim.skimage.filters def main(args): pfile = "cucim_filters_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ # _gabor.py ( "gabor", dict(n_stds=3), dict(frequency=[0.075, 0.1, 0.2, 0.3]), False, False, ), # _gaussian.py ( "gaussian", dict(truncate=4.0, preserve_range=True), dict(sigma=[0.25, 1, 4]), True, True, ), # _median.py ("median", dict(mode="nearest"), dict(), False, True), # _rank_order.py ("rank_order", dict(), dict(), False, True), # _unsharp_mask.py ( "unsharp_mask", dict(), dict(radius=[0.5, 1.0, 2.0, 3.0]), True, True, ), # edges.py ("sobel", dict(), dict(axis=[None, 0, -1]), False, True), ("prewitt", dict(), dict(axis=[None, 0, -1]), False, True), ("scharr", dict(), dict(axis=[None, 0, -1]), False, True), ("roberts", dict(), dict(), False, False), ("roberts_pos_diag", dict(), dict(), False, False), ("roberts_neg_diag", dict(), dict(), False, False), ("farid", dict(), dict(), False, False), ("laplace", dict(ksize=3), dict(), False, True), # lpi_filter.py # TODO: benchmark wiener # ridges.py # TODO: Had to set meijering, etc allow_nd to False just due to # insufficient GPU memory ( "meijering", dict(sigmas=range(1, 10, 2), alpha=None), dict(black_ridges=[True, False], mode=["reflect"]), False, False, ), ( "sato", dict(sigmas=range(1, 10, 2)), dict(black_ridges=[True, False], mode=["reflect"]), False, False, ), ( "frangi", dict(sigmas=range(1, 10, 2)), dict(black_ridges=[True, False], mode=["reflect"]), False, False, ), ( "hessian", dict(sigmas=range(1, 10, 2)), dict(black_ridges=[True, False], mode=["reflect"]), False, False, ), # thresholding.py ("threshold_isodata", dict(), dict(nbins=[64, 256]), False, True), ("threshold_otsu", dict(), dict(nbins=[64, 256]), False, True), ("threshold_yen", dict(), dict(nbins=[64, 256]), False, True), # TODO: threshold_local should support n-dimensional data ( "threshold_local", dict(), dict(block_size=[5, 15], method=["gaussian", "mean", "median"]), False, False, ), ("threshold_li", dict(), dict(), False, True), ("threshold_minimum", dict(), dict(nbins=[64, 256]), False, True), ("threshold_mean", dict(), dict(), False, True), ("threshold_triangle", dict(), dict(nbins=[64, 256]), False, True), ( "threshold_niblack", dict(), dict(window_size=[7, 15, 65]), False, True, ), ( "threshold_sauvola", dict(), dict(window_size=[7, 15, 65]), False, True, ), ( "apply_hysteresis_threshold", dict(low=0.15, high=0.6), dict(), False, True, ), ( "threshold_multiotsu", dict(), dict(nbins=[64, 256], classes=[3]), False, True, ), ]: if function_name != args.func_name: continue else: # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) if function_name in ["gaussian", "unsharp_mask"]: fixed_kwargs["channel_axis"] = -1 if shape[-1] == 3 else None ndim = len(shape) if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue if function_name == "gabor" and np.prod(shape) > 1000000: # avoid cases that are too slow on the CPU var_kwargs["frequency"] = [ f for f in var_kwargs["frequency"] if f >= 0.1 ] if function_name == "median": footprints = [] ndim = len(shape) footprint_sizes = [3, 5, 7, 9] if ndim == 2 else [3, 5, 7] for footprint_size in footprint_sizes: footprints.append(np.ones((footprint_size,) * ndim, dtype=bool)) var_kwargs["footprint"] = footprints if function_name in ["gaussian", "unsharp_mask"]: fixed_kwargs["channel_axis"] = -1 if shape[-1] == 3 else None B = ImageBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.filters, module_gpu=cucim.skimage.filters, run_cpu=not args.no_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Benchmarking cuCIM Filters") func_name_choices = [ "gabor", "gaussian", "median", "rank_order", "unsharp_mask", "sobel", "prewitt", "scharr", "roberts", "roberts_pos_diag", "roberts_neg_diag", "farid", "laplace", "meijering", "sato", "frangi", "hessian", "threshold_isodata", "threshold_otsu", "threshold_yen", "threshold_local", "threshold_li", "threshold_minimum", "threshold_mean", "threshold_triangle", "threshold_niblack", "threshold_sauvola", "apply_hysteresis_threshold", "threshold_multiotsu", ] dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help="Size of input image", required=True ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cupyx_scipy_ndimage_fourier_bench.py
import os import pickle import cupy import cupy as cp import numpy as np import pandas as pd from _image_bench import ImageBench pfile = "fourier_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.float32] for shape in [(512, 512), (3840, 2160), (192, 192, 192)]: # shape = (200, 200, 200) ndim = len(shape) class FourierBench(ImageBench): def set_args(self, dtype): cplx_dt = np.promote_types(dtype, np.complex64) imaged = cupy.testing.shaped_random( self.shape, xp=cp, dtype=cplx_dt ) image = cp.asnumpy(imaged) self.args_cpu = (image,) self.args_gpu = (imaged,) for fname, fixed_kwargs, var_kwargs in [ ("fourier_gaussian", dict(sigma=5), {}), ("fourier_uniform", dict(size=16), {}), ("fourier_shift", dict(shift=5), {}), ("fourier_ellipsoid", dict(size=15.0), {}), ]: B = FourierBench( function_name=fname, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, ) results = B.run_benchmark(duration=1) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown())
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-segmentation.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) # these require an integer-valued label image param_filt=(clear_border expand_labels relabel_sequential find_boundaries mark_boundaries random_walker) param_dt=(float32) param_dt_label=(uint8 uint32) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do for dt_label in "${param_dt_label[@]}"; do python cucim_segmentation_bench.py -f $filt -i $shape -d $dt --dtype_label $dt_label -t 10 done done done done # these do not require an integer-valued input image param_filt=(inverse_gaussian_gradient morphological_geodesic_active_contour morphological_chan_vese chan_vese) param_dt=(float32) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_segmentation_bench.py -f $filt -i $shape -d $dt -t 10 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cupyx_scipy_ndimage_measurements_bench.py
import math import os import pickle import cupy import cupy as cp import cupyx.scipy.ndimage import numpy as np import pandas as pd import scipy import scipy.ndimage as ndi from _image_bench import ImageBench class LabelBench(ImageBench): def __init__( self, function_name, shape, structure=None, contiguous_labels=True, dtypes=np.float32, fixed_kwargs={}, var_kwargs={}, index_str=None, module_cpu=scipy.ndimage, module_gpu=cupyx.scipy.ndimage, ): self.contiguous_labels = contiguous_labels array_kwargs = dict(structure=structure) if "structure" in fixed_kwargs: raise ValueError("fixed_kwargs cannot contain 'structure'") fixed_kwargs.update(array_kwargs) super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=module_cpu, module_gpu=module_gpu, ) def set_args(self, dtype): a = np.array( [ [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 4, 0], [2, 2, 0, 0, 3, 0, 4, 4], [0, 0, 0, 0, 0, 5, 0, 0], ] ) tiling = tuple(s // a_s for s, a_s in zip(shape, a.shape)) if self.contiguous_labels: image = np.kron(a, np.ones(tiling, dtype=a.dtype)) else: image = np.tile(a, tiling) imaged = cp.asarray(image) self.args_cpu = (image,) self.args_gpu = (imaged,) class MeasurementsBench(ImageBench): def __init__( self, function_name, shape, use_index=False, nlabels=16, dtypes=[np.float32], fixed_kwargs={}, var_kwargs={}, index_str=None, module_cpu=scipy.ndimage, module_gpu=cupyx.scipy.ndimage, ): self.nlabels = nlabels self.use_index = use_index super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=module_cpu, module_gpu=module_gpu, ) def set_args(self, dtype): size = math.prod(self.shape) imaged = cupy.arange(size, dtype=dtype).reshape(self.shape) labelsd = cupy.random.choice(self.nlabels, size) labelsd = labelsd.reshape(self.shape) + 1 image = cp.asnumpy(imaged) labels = cp.asnumpy(labelsd) if self.use_index: indexd = cupy.arange(1, self.nlabels + 1, dtype=cupy.intp) index = cp.asnumpy(indexd) else: indexd = None index = None self.args_cpu = (image,) self.args_gpu = (imaged,) # store labels and index as fixed_kwargs since histogram does not use # them in the same position self.fixed_kwargs_gpu.update(dict(labels=labelsd, index=indexd)) self.fixed_kwargs_cpu.update(dict(labels=labels, index=index)) pfile = "measurements_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.float32] for shape in [(512, 512), (3840, 2160), (192, 192, 192)]: ndim = len(shape) for fname, var_kwargs in [ ( "label", {}, ), # dict(greyscale_mode=[False, True]) not available in cupyx ]: for contiguous_labels in [True, False]: if contiguous_labels: index_str = "contiguous" else: index_str = None B = LabelBench( function_name=fname, shape=shape, dtypes=dtypes, structure=ndi.generate_binary_structure(ndim, ndim), contiguous_labels=contiguous_labels, index_str=index_str, fixed_kwargs=dict(output=None), var_kwargs=var_kwargs, ) results = B.run_benchmark(duration=1) all_results = pd.concat([all_results, results["full"]]) for fname in [ "sum", "mean", "variance", "standard_deviation", "minimum", "minimum_position", "maximum", "maximum_position", "median", "extrema", "center_of_mass", ]: for use_index in [True, False]: if use_index: nlabels_cases = [4, 16, 64, 256] else: nlabels_cases = [16] for nlabels in nlabels_cases: if use_index: index_str = f"{nlabels} labels, no index" else: index_str = f"{nlabels} labels, with index" B = MeasurementsBench( function_name=fname, shape=shape, dtypes=dtypes, use_index=use_index, nlabels=nlabels, index_str=index_str, var_kwargs=var_kwargs, ) results = B.run_benchmark(duration=1) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown())
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-measure.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) param_filt=(label regionprops moments moments_central centroid inertia_tensor inertia_tensor_eigvals block_reduce shannon_entropy profile_line) param_dt=(float32 uint8) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_measure_bench.py -f $filt -i $shape -d $dt -t 10 done done done # # commenting out colocalization metrics below this point # # (scikit-image 0.20 is not yet officially released) # param_shape=(512,512 3840,2160 192,192,192) # param_filt=(manders_coloc_coeff manders_overlap_coeff pearson_corr_coeff) # param_dt=(float32 uint8) # for shape in "${param_shape[@]}"; do # for filt in "${param_filt[@]}"; do # for dt in "${param_dt[@]}"; do # python cucim_measure_bench.py -f $filt -i $shape -d $dt -t 10 # done # done # done # # only supports binary-valued images # param_shape=(512,512 3840,2160 192,192,192) # param_filt=(intersection_coeff) # param_dt=(bool) # for shape in "${param_shape[@]}"; do # for filt in "${param_filt[@]}"; do # for dt in "${param_dt[@]}"; do # python cucim_measure_bench.py -f $filt -i $shape -d $dt -t 10 # done # done # done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_registration_bench.py
import argparse import math import os import pickle import cupy as cp import numpy as np import pandas as pd import skimage import skimage.registration from _image_bench import ImageBench import cucim.skimage import cucim.skimage.registration class RegistrationBench(ImageBench): def set_args(self, dtype): if np.dtype(dtype).kind in "iu": im1 = skimage.data.camera() else: im1 = skimage.data.camera() / 255.0 im1 = im1.astype(dtype) if len(self.shape) == 3: im1 = im1[..., np.newaxis] n_tile = [math.ceil(s / im_s) for s, im_s in zip(self.shape, im1.shape)] slices = tuple([slice(s) for s in self.shape]) image = np.tile(im1, n_tile)[slices] image2 = np.roll(image, (10, 20)) imaged = cp.asarray(image) imaged2 = cp.asarray(image2) self.args_cpu = (image, image2) self.args_gpu = (imaged, imaged2) def main(args): pfile = "cucim_registration_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) run_cpu = not args.no_cpu for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ # _phase_cross_correlation.py ("phase_cross_correlation", dict(), dict(), False, True), # optical flow functions ( "optical_flow_tvl1", dict(), dict(num_iter=[10], num_warp=[5]), False, True, ), ( "optical_flow_ilk", dict(), dict( radius=[3, 7], num_warp=[10], gaussian=[False, True], prefilter=[False, True], ), False, True, ), ]: if function_name != args.func_name: continue if function_name == "phase_cross_correlation": ndim = len(shape) if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue for masked in [True, False]: index_str = f"masked={masked}" if masked: moving_mask = cp.ones(shape, dtype=bool) moving_mask[20:-20, :] = 0 moving_mask[:, 20:-20] = 0 reference_mask = cp.ones(shape, dtype=bool) reference_mask[80:-80, :] = 0 reference_mask[:, 80:-80] = 0 fixed_kwargs["moving_mask"] = moving_mask fixed_kwargs["reference_mask"] = reference_mask else: fixed_kwargs["moving_mask"] = None fixed_kwargs["reference_mask"] = None B = RegistrationBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=skimage.registration, module_gpu=cucim.skimage.registration, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) else: ndim = len(shape) if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue B = RegistrationBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.registration, module_gpu=cucim.skimage.registration, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) try: import tabular # noqa: F401 with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) except ImportError: pass if __name__ == "__main__": parser = argparse.ArgumentParser( description="Benchmarking cuCIM registration functions" ) func_name_choices = [ "phase_cross_correlation", "optical_flow_tvl1", "optical_flow_ilk", ] dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help=( "Size of input image (omit color channel, it will be appended " "as needed)" ), required=True, ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cupyx_scipy_ndimage_interp_bench.py
import math import os import pickle import cupy import cupy as cp import numpy as np import pandas as pd from _image_bench import ImageBench class InterpolationBench(ImageBench): def set_args(self, dtype): imaged = cupy.testing.shaped_random(self.shape, xp=cp, dtype=dtype) image = cp.asnumpy(imaged) self.args_cpu = (image,) self.args_gpu = (imaged,) class MapCoordinatesBench(ImageBench): def set_args(self, dtype): imaged = cupy.testing.shaped_random(self.shape, xp=cp, dtype=dtype) image = cp.asnumpy(imaged) rstate = cp.random.RandomState(5) ndim = len(self.shape) coordsd = cp.indices(self.shape) + 0.1 * rstate.standard_normal( (ndim,) + self.shape ) coords = cupy.asnumpy(coordsd) self.args_cpu = (image, coords) self.args_gpu = (imaged, coordsd) pfile = "interp_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() orders = [0, 1, 3, 5] # 2, 3, 4, 5] modes = ["constant", "reflect"] prefilter = True dtypes = [np.float32] # (4608, 3456) = 16MP as in IPOL paper for shape in [(512, 512), (3840, 2160), (4608, 3456), (192, 192, 192)]: ndim = len(shape) B = MapCoordinatesBench( function_name="map_coordinates", shape=shape, dtypes=dtypes, fixed_kwargs=dict(output=None, prefilter=prefilter), var_kwargs=dict(mode=modes, order=orders), ) results = B.run_benchmark(duration=1) all_results = pd.concat([all_results, results["full"]]) for fname, fixed_kwargs, var_kwargs in [ ( "affine_transform1", # see special case below dict(output=None, output_shape=None, prefilter=prefilter), dict(mode=modes, order=orders), ), ( "affine_transform2", # see special case below dict(output=None, output_shape=None, prefilter=prefilter), dict(mode=modes, order=orders), ), ( "zoom", dict(output=None, zoom=1.1, prefilter=prefilter), dict(mode=modes, order=orders), ), ( "shift", dict(output=None, shift=1.5, prefilter=prefilter), dict(mode=modes, order=orders), ), ( "rotate", dict( output=None, reshape=True, axes=(0, 1), angle=30, prefilter=prefilter, ), dict(mode=modes, order=orders), ), ( "spline_filter", dict(output=np.float32), dict( mode=[ "mirror", ], order=[2, 3, 4, 5], ), ), ( "spline_filter1d", dict(output=np.float32), dict( mode=[ "mirror", ], order=[2, 3, 4, 5], axis=[0, -1], ), ), ]: if fname == "affine_transform1": # affine_transform case 1: the general affine matrix code path fname = fname[:-1] ndim = len(shape) angle = np.deg2rad(30) cos = math.cos(angle) sin = math.cos(angle) matrix = np.identity(ndim) axes = (0, 1) matrix[axes[0], axes[0]] = cos matrix[axes[0], axes[1]] = sin matrix[axes[1], axes[0]] = -sin matrix[axes[1], axes[1]] = cos offset = np.full((ndim,), 1.5, dtype=float) fixed_kwargs["matrix"] = matrix fixed_kwargs["offset"] = offset elif fname == "affine_transform2": # affine_transform case 2: exercises the zoom + shift code path fname = fname[:-1] if len(shape) == 2: matrix = np.asarray([0.5, 2.0]) offset = np.asarray([20.0, -25.0]) elif len(shape) == 3: matrix = np.asarray([0.5, 2.0, 0.6]) offset = np.asarray([0.0, -5.0, 15]) fixed_kwargs["matrix"] = matrix fixed_kwargs["offset"] = offset B = InterpolationBench( function_name=fname, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, ) results = B.run_benchmark(duration=1) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown())
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-morphology.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) param_filt=(binary_erosion binary_dilation binary_opening binary_closing isotropic_erosion isotropic_dilation isotropic_opening isotropic_closing remove_small_objects remove_small_holes erosion dilation opening closing white_tophat black_tophat medial_axis thin reconstruction) param_dt=(uint8) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_morphology_bench.py -f $filt -i $shape -d $dt -t 4 done done done # Note: Omit binary_*, medial_axis and thin from floating point benchmarks. # (these functions only take binary input). param_filt_float=(remove_small_objects remove_small_holes erosion dilation opening closing white_tophat black_tophat reconstruction) param_dt=(float32) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_morphology_bench.py -f $filt -i $shape -d $dt -t 4 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-registration.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) param_filt=(phase_cross_correlation optical_flow_tvl1 optical_flow_ilk) param_dt=(float32 uint8) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_registration_bench.py -f $filt -i $shape -d $dt -t 10 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_color_bench.py
import argparse import os import pickle import cupy import cupy as cp import cupyx.scipy.ndimage import numpy as np import pandas as pd import scipy import skimage import skimage.color from _image_bench import ImageBench import cucim.skimage import cucim.skimage.color func_name_choices = [ "convert_colorspace", "rgb2hed", "hed2rgb", "lab2lch", "lch2lab", "xyz2lab", "lab2xyz", "rgba2rgb", "label2rgb", ] class ColorBench(ImageBench): def set_args(self, dtype): if self.shape[-1] != 3: raise ValueError("shape must be 3 on the last axis") imaged = cupy.testing.shaped_random( self.shape, xp=cp, dtype=dtype, scale=1.0 ) image = cp.asnumpy(imaged) self.args_cpu = (image,) self.args_gpu = (imaged,) class RGBABench(ImageBench): def set_args(self, dtype): if self.shape[-1] != 4: raise ValueError("shape must be 4 on the last axis") imaged = cupy.testing.shaped_random( self.shape, xp=cp, dtype=dtype, scale=1.0 ) image = cp.asnumpy(imaged) self.args_cpu = (image,) self.args_gpu = (imaged,) class LabelBench(ImageBench): def __init__( self, function_name, shape, contiguous_labels=True, dtypes=np.float32, fixed_kwargs={}, var_kwargs={}, index_str=None, module_cpu=scipy.ndimage, module_gpu=cupyx.scipy.ndimage, run_cpu=True, ): self.contiguous_labels = contiguous_labels super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=module_cpu, module_gpu=module_gpu, run_cpu=run_cpu, ) def set_args(self, dtype): a = np.array( [ [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 4, 0], [2, 2, 0, 0, 3, 0, 4, 4], [0, 0, 0, 0, 0, 5, 0, 0], ], dtype=int, ) tiling = tuple(s // a_s for s, a_s in zip(self.shape, a.shape)) if self.contiguous_labels: label = np.kron(a, np.ones(tiling, dtype=a.dtype)) else: label = np.tile(a, tiling) labelled = cp.asarray(label) imaged = cupy.testing.shaped_random( labelled.shape, xp=cp, dtype=dtype, scale=1.0 ) image = cp.asnumpy(imaged) self.args_cpu = ( label, image, ) self.args_gpu = ( labelled, imaged, ) def main(args): pfile = "cucim_color_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) run_cpu = not args.no_cpu all_colorspaces = False for function_name in func_name_choices: if function_name != args.func_name: continue if function_name == "convert_colorspace": if all_colorspaces: color_spaces = [ "RGB", "HSV", "RGB CIE", "XYZ", "YUV", "YIQ", "YPbPr", "YCbCr", "YDbDr", ] else: color_spaces = ["RGB", "HSV", "YUV", "XYZ"] for fromspace in color_spaces: for tospace in color_spaces: if fromspace == tospace: continue B = ColorBench( function_name="convert_colorspace", shape=shape + (3,), dtypes=dtypes, fixed_kwargs=dict(fromspace=fromspace, tospace=tospace), var_kwargs={}, index_str=f"{fromspace.lower()}2{tospace.lower()}", module_cpu=skimage.color, module_gpu=cucim.skimage.color, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) elif function_name == "rgba2rgb": B = RGBABench( function_name="rgba2rgb", shape=shape[:-1] + (4,), dtypes=dtypes, fixed_kwargs={}, var_kwargs={}, module_cpu=skimage.color, module_gpu=cucim.skimage.color, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) elif function_name == "label2rgb": for contiguous_labels in [True, False]: if contiguous_labels: index_str = "contiguous" else: index_str = None B = LabelBench( function_name="label2rgb", shape=shape, dtypes=dtypes, contiguous_labels=contiguous_labels, index_str=index_str, fixed_kwargs=dict(bg_label=0), var_kwargs=dict(kind=["avg", "overlay"]), module_cpu=skimage.color, module_gpu=cucim.skimage.color, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) elif function_name in [ "rgb2hed", "hed2rgb", "lab2lch", "lch2lab", "xyz2lab", "lab2xyz", ]: B = ColorBench( function_name=function_name, shape=shape + (3,), dtypes=dtypes, fixed_kwargs={}, var_kwargs={}, module_cpu=skimage.color, module_gpu=cucim.skimage.color, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) try: import tabular # noqa: F401 with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) except ImportError: pass if __name__ == "__main__": parser = argparse.ArgumentParser( description="Benchmarking cuCIM color conversion functions" ) dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help=( "Size of input image (omit color channel, it will be appended " "as needed)" ), required=True, ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/requirements-bench.txt
pandas>=1.0 tabulate>=0.8.7
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_restoration_bench.py
import argparse import math import os import pickle import cupy as cp import cupyx.scipy.ndimage as ndi import numpy as np import pandas as pd import skimage import skimage.restoration from _image_bench import ImageBench from skimage.restoration import denoise_tv_chambolle as tv_cpu import cucim.skimage import cucim.skimage.restoration from cucim.skimage.restoration import denoise_tv_chambolle as tv_gpu class DenoiseBench(ImageBench): def set_args(self, dtype): if np.dtype(dtype).kind in "iu": im1 = skimage.data.camera() else: im1 = skimage.data.camera() / 255.0 im1 = im1.astype(dtype) if len(self.shape) == 3: im1 = im1[..., np.newaxis] # add noise if np.dtype(dtype).kind in "iu": sigma = 0.05 * 255 im1 = im1 + sigma * np.random.randn(*im1.shape) im1 = np.clip(im1, 0, 255).astype(dtype) else: sigma = 0.05 im1 = im1 + sigma * np.random.randn(*im1.shape) n_tile = [math.ceil(s / im_s) for s, im_s in zip(self.shape, im1.shape)] slices = tuple([slice(s) for s in self.shape]) image = np.tile(im1, n_tile)[slices] imaged = cp.asarray(image) self.args_cpu = (image,) self.args_gpu = (imaged,) class CalibratedDenoiseBench(ImageBench): def set_args(self, dtype): if np.dtype(dtype).kind in "iu": im1 = skimage.data.camera() else: im1 = skimage.data.camera() / 255.0 im1 = im1.astype(dtype) if len(self.shape) == 3: im1 = im1[..., np.newaxis] # add noise if np.dtype(dtype).kind in "iu": sigma = 0.05 * 255 im1 = im1 + sigma * np.random.randn(*im1.shape) im1 = np.clip(im1, 0, 255).astype(dtype) else: sigma = 0.05 im1 = im1 + sigma * np.random.randn(*im1.shape) n_tile = [math.ceil(s / im_s) for s, im_s in zip(self.shape, im1.shape)] slices = tuple([slice(s) for s in self.shape]) image = np.tile(im1, n_tile)[slices] imaged = cp.asarray(image) denoise_parameters = {"weight": np.linspace(0.01, 0.4, 10)} self.args_cpu = (image, tv_cpu, denoise_parameters) self.args_gpu = (imaged, tv_gpu, denoise_parameters) class DeconvolutionBench(ImageBench): def set_args(self, dtype): if np.dtype(dtype).kind in "iu": im1 = skimage.data.camera() else: im1 = skimage.data.camera() / 255.0 im1 = im1.astype(dtype) if len(self.shape) == 3: im1 = im1[..., np.newaxis] im1 = cp.array(im1) n_tile = [math.ceil(s / im_s) for s, im_s in zip(self.shape, im1.shape)] slices = tuple([slice(s) for s in self.shape]) imaged = cp.tile(im1, n_tile)[slices] psfd = cp.ones((5,) * imaged.ndim) / 25 imaged = ndi.convolve(imaged, psfd) image = cp.asnumpy(imaged) psf = cp.asnumpy(psfd) self.args_cpu = (image, psf) self.args_gpu = (imaged, psfd) def main(args): pfile = "cucim_restoration_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) run_cpu = not args.no_cpu for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ # _denoise.py ("denoise_tv_chambolle", dict(), dict(weight=[0.02]), True, True), # j_invariant.py ("calibrate_denoiser", dict(), dict(), False, True), # deconvolution.py ("wiener", dict(balance=100.0), dict(), False, False), ("unsupervised_wiener", dict(), dict(), False, False), ("richardson_lucy", dict(), dict(num_iter=[5]), False, True), ]: if function_name != args.func_name: continue ndim = len(shape) if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue if function_name in ["denoise_tv_chambolle", "calibrate_denoiser"]: if function_name == "denoise_tv_chambolle": fixed_kwargs["channel_axis"] = -1 if shape[-1] == 3 else None if function_name == "calibrate_denoiser": denoise_class = CalibratedDenoiseBench else: denoise_class = DenoiseBench B = denoise_class( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.restoration, module_gpu=cucim.skimage.restoration, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) elif function_name in [ "wiener", "unsupervised_wiener", "richardson_lucy", ]: B = DeconvolutionBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.restoration, module_gpu=cucim.skimage.restoration, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) try: import tabular # noqa: F401 with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) except ImportError: pass if __name__ == "__main__": parser = argparse.ArgumentParser( description="Benchmarking cuCIM restoration functions" ) func_name_choices = [ "denoise_tv_chambolle", "calibrate_denoiser", "wiener", "unsupervised_wiener", "richardson_lucy", ] dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help=( "Size of input image (omit color channel, it will be appended " "as needed)" ), required=True, ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_measure_bench.py
import argparse import math import os import pickle import cupy as cp import numpy as np import pandas as pd import skimage import skimage.measure from _image_bench import ImageBench from cucim_metrics_bench import MetricsBench import cucim.skimage import cucim.skimage.measure class LabelBench(ImageBench): def __init__( self, function_name, shape, contiguous_labels=True, dtypes=np.float32, fixed_kwargs={}, var_kwargs={}, index_str=None, module_cpu=skimage.measure, module_gpu=cucim.skimage.measure, run_cpu=True, ): self.contiguous_labels = contiguous_labels super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=module_cpu, module_gpu=module_gpu, run_cpu=run_cpu, ) def set_args(self, dtype): a = np.array( [ [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 4, 0], [2, 2, 0, 0, 3, 0, 4, 4], [0, 0, 0, 0, 0, 5, 0, 0], ] ) tiling = tuple(s // a_s for s, a_s in zip(self.shape, a.shape)) if self.contiguous_labels: image = np.kron(a, np.ones(tiling, dtype=a.dtype)) else: image = np.tile(a, tiling) imaged = cp.asarray(image) self.args_cpu = (image,) self.args_gpu = (imaged,) class RegionpropsBench(ImageBench): def __init__( self, function_name, shape, contiguous_labels=True, dtypes=np.float32, fixed_kwargs={}, var_kwargs={}, index_str=None, module_cpu=skimage.measure, module_gpu=cucim.skimage.measure, run_cpu=True, ): self.contiguous_labels = contiguous_labels super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=module_cpu, module_gpu=module_gpu, run_cpu=run_cpu, ) def set_args(self, dtype): a = np.array( [ [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 4, 0], [2, 2, 0, 0, 3, 0, 4, 4], [0, 0, 0, 0, 0, 5, 0, 0], ] ) tiling = tuple(s // a_s for s, a_s in zip(self.shape, a.shape)) if self.contiguous_labels: image = np.kron(a, np.ones(tiling, dtype=a.dtype)) else: image = np.tile(a, tiling) imaged = cp.asarray(image) label_dev = cucim.skimage.measure.label(imaged).astype(int) label = cp.asnumpy(label_dev) self.args_cpu = (label, image) self.args_gpu = (label_dev, imaged) class FiltersBench(ImageBench): def set_args(self, dtype): if np.dtype(dtype).kind in "iu": im1 = skimage.data.camera() else: im1 = skimage.data.camera() / 255.0 im1 = im1.astype(dtype) if len(self.shape) == 3: im1 = im1[..., np.newaxis] n_tile = [math.ceil(s / im_s) for s, im_s in zip(self.shape, im1.shape)] slices = tuple([slice(s) for s in self.shape]) image = np.tile(im1, n_tile)[slices] imaged = cp.asarray(image) assert imaged.dtype == dtype assert imaged.shape == self.shape self.args_cpu = (image,) self.args_gpu = (imaged,) class BinaryImagePairBench(ImageBench): def set_args(self, dtype): rng = cp.random.default_rng(seed=123) img0d = rng.integers(0, 2, self.shape, dtype=cp.uint8).view(bool) img1d = rng.integers(0, 2, self.shape, dtype=cp.uint8).view(bool) img0 = cp.asnumpy(img0d) img1 = cp.asnumpy(img1d) self.args_cpu = (img0, img1) self.args_gpu = (img0d, img1d) class MandersColocBench(ImageBench): def set_args(self, dtype): # image imaged = cp.testing.shaped_arange(self.shape, dtype=dtype) imaged = imaged / imaged.max() # binary mask rng = cp.random.default_rng(seed=123) maskd = rng.integers(0, 2, self.shape, dtype=cp.uint8).view(bool) self.args_cpu = (cp.asnumpy(imaged), cp.asnumpy(maskd)) self.args_gpu = (imaged, maskd) def main(args): pfile = "cucim_measure_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) run_cpu = not args.no_cpu for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ # _gaussian.py ( "label", dict(return_num=False, background=0), dict(connectivity=[1, 2]), False, True, ), # regionprops.py ("regionprops", dict(), dict(), False, True), # _moments.py ("moments", dict(), dict(order=[1, 2, 3, 4]), False, False), ("moments_central", dict(), dict(order=[1, 2, 3]), False, True), # omitted from benchmarks (only tiny arrays): moments_normalized, moments_hu # noqa: E501 ("centroid", dict(), dict(), False, True), ("inertia_tensor", dict(), dict(), False, True), ("inertia_tensor_eigvals", dict(), dict(), False, True), # _polygon.py # TODO: approximate_polygon, subdivide_polygon # block.py ( "block_reduce", dict(), dict( func=[ cp.sum, ] ), True, True, ), # variable block_size configured below # entropy.py ("shannon_entropy", dict(base=2), dict(), True, True), # profile.py ( "profile_line", dict(src=(5, 7)), dict(reduce_func=[cp.mean], linewidth=[1, 2, 4], order=[1, 3]), True, False, ), # variable block_size configured below # binary image overlap measures ("intersection_coeff", dict(mask=None), dict(), False, True), ("manders_coloc_coeff", dict(mask=None), dict(), False, True), ("manders_overlap_coeff", dict(mask=None), dict(), False, True), ("pearson_corr_coeff", dict(mask=None), dict(), False, True), ]: if function_name != args.func_name: continue ndim = len(shape) if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue if function_name in ["label", "regionprops"]: Tester = ( LabelBench if function_name == "label" else RegionpropsBench ) for contiguous_labels in [True, False]: if contiguous_labels: index_str = "contiguous" else: index_str = None B = Tester( function_name=function_name, shape=shape, dtypes=dtypes, contiguous_labels=contiguous_labels, index_str=index_str, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.measure, module_gpu=cucim.skimage.measure, run_cpu=run_cpu, ) elif function_name in [ "intersection_coeff", "manders_coloc_coeff", "manders_overlap_coeff", "pearson_corr_coeff", ]: if function_name in ["pearson_corr_coeff", "manders_overlap_coeff"]: # arguments are two images of matching dtype Tester = MetricsBench elif function_name == "manders_coloc_coeff": # arguments are one image + binary mask Tester = MandersColocBench else: # arguments are two binary images Tester = BinaryImagePairBench B = Tester( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.measure, module_gpu=cucim.skimage.measure, run_cpu=run_cpu, ) else: if function_name == "gabor" and np.prod(shape) > 1000000: # avoid cases that are too slow on the CPU var_kwargs["frequency"] = [ f for f in var_kwargs["frequency"] if f >= 0.1 ] if function_name == "block_reduce": ndim = len(shape) if shape[-1] == 3: block_sizes = [ (b,) * (ndim - 1) + (3,) for b in (16, 32, 64) ] else: block_sizes = [(b,) * ndim for b in (16, 32, 64)] var_kwargs["block_size"] = block_sizes if function_name == "profile_line": fixed_kwargs["dst"] = (shape[0] - 32, shape[1] + 9) if function_name == "median": footprints = [] ndim = len(shape) footprint_sizes = [3, 5, 7, 9] if ndim == 2 else [3, 5, 7] for footprint_size in [3, 5, 7, 9]: footprints.append( np.ones((footprint_sizes,) * ndim, dtype=bool) ) var_kwargs["footprint"] = footprints if function_name in ["gaussian", "unsharp_mask"]: fixed_kwargs["channel_axis"] = -1 if shape[-1] == 3 else None B = FiltersBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.measure, module_gpu=cucim.skimage.measure, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Benchmarking cuCIM measure functions" ) func_name_choices = [ "label", "regionprops", "moments", "moments_central", "centroid", "inertia_tensor", "inertia_tensor_eigvals", "block_reduce", "shannon_entropy", "profile_line", "intersection_coeff", "manders_coloc_coeff", "manders_overlap_coeff", "pearson_corr_coeff", ] dtype_choices = [ "bool", "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help="Size of input image", required=True ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_metrics_bench.py
import argparse import os import pickle import cupy as cp import numpy as np import pandas as pd import skimage import skimage.metrics from _image_bench import ImageBench import cucim.skimage import cucim.skimage.metrics from cucim.skimage import data, measure class MetricsBench(ImageBench): def set_args(self, dtype): imaged = cp.testing.shaped_arange(self.shape, dtype=dtype) imaged2 = cp.testing.shaped_arange(self.shape, dtype=dtype) imaged2 = imaged2 + 0.05 * cp.random.standard_normal(self.shape) imaged = imaged / imaged.max() imaged2 = imaged2 / imaged2.max() imaged2 = imaged2.clip(0, 1.0) self.args_cpu = (cp.asnumpy(imaged), cp.asnumpy(imaged2)) self.args_gpu = (imaged, imaged2) class SegmentationMetricBench(ImageBench): def __init__( self, function_name, shape, dtypes=np.float32, fixed_kwargs={}, var_kwargs={}, index_str=None, module_cpu=skimage.metrics, module_gpu=cucim.skimage.metrics, run_cpu=True, ): super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=module_cpu, module_gpu=module_gpu, run_cpu=run_cpu, ) def _generate_labels(self, dtype, rng=5): ndim = len(self.shape) blobs_kwargs = dict( blob_size_fraction=0.05, volume_fraction=0.35, rng=rng ) # binary blobs only creates square outputs labels = measure.label( data.binary_blobs(max(self.shape), n_dim=ndim, **blobs_kwargs) ) print(f"# labels generated = {labels.max()}") # crop to rectangular labels = labels[tuple(slice(s) for s in self.shape)] return labels.astype(dtype, copy=False) def set_args(self, dtype): labels1_d = self._generate_labels(dtype, rng=5) labels2_d = self._generate_labels(dtype, rng=3) labels1 = cp.asnumpy(labels1_d) labels2 = cp.asnumpy(labels2_d) self.args_cpu = (labels1, labels2) self.args_gpu = (labels1_d, labels2_d) def main(args): pfile = "cucim_metrics_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) run_cpu = not args.no_cpu for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ # _structural_similarity.py ( "structural_similarity", dict(data_range=1.0), dict(gradient=[False, True], gaussian_weights=[False, True]), True, True, ), # simple_metrics.py ("mean_squared_error", dict(), dict(), True, True), ( "normalized_root_mse", dict(), dict(normalization=["euclidean", "min-max", "mean"]), True, True, ), ("peak_signal_noise_ratio", dict(data_range=1.0), dict(), True, True), ("normalized_mutual_information", dict(bins=100), dict(), True, True), ("adapted_rand_error", dict(), dict(), False, True), ( "contingency_table", dict(), dict(normalize=[False, True]), False, True, ), ("variation_of_information", dict(), dict(), False, True), ]: if function_name != args.func_name: continue ndim = len(shape) if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue if function_name in ["structural_similarity"]: fixed_kwargs["channel_axis"] = -1 if shape[-1] == 3 else None if function_name in [ "structural_similarity", "mean_squared_error", "normalized_root_mse", "peak_signal_noise_ratio", "normalized_mutual_information", ]: B = MetricsBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.metrics, module_gpu=cucim.skimage.metrics, run_cpu=run_cpu, ) elif function_name in [ "adapted_rand_error", "contingency_table", "variation_of_information", ]: B = SegmentationMetricBench( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.metrics, module_gpu=cucim.skimage.metrics, run_cpu=run_cpu, ) else: raise ValueError( f"benchmark function not configured for {function_name}" ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Benchmarking cuCIM metrics functions" ) func_name_choices = [ "structural_similarity", "mean_squared_error", "normalized_root_mse", "peak_signal_noise_ratio", "normalized_mutual_information", "adapted_rand_error", "contingency_table", "variation_of_information", ] # noqa dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help="Size of input image", required=True ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-all.sh
for file in ./cu*py do echo $file time python "$file" done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-transform.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) param_filt=(resize resize_local_mean rescale rotate downscale_local_mean warp_polar integral_image pyramid_gaussian pyramid_laplacian) param_dt=(float32 uint8) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_transform_bench.py -f $filt -i $shape -d $dt -t 10 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-color.sh
#!/bin/bash param_shape=(512,512 3840,2160 192,192,192) param_filt=(convert_colorspace rgb2hed hed2rgb lab2lch lch2lab xyz2lab lab2xyz rgba2rgb label2rgb) param_dt=(float32 uint8) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_color_bench.py -f $filt -i $shape -d $dt -t 10 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/run-nv-bench-metrics.sh
#!/bin/bash param_shape=(512,512 3840,2160 3840,2160,3 192,192,192) param_filt=(structural_similarity mean_squared_error normalized_root_mse peak_signal_noise_ratio normalized_mutual_information) param_dt=(float32 uint8) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_metrics_bench.py -f $filt -i $shape -d $dt -t 4 done done done # can only use integer dtypes and non-color images for the segmentation metrics param_shape=(512,512 3840,2160 192,192,192) param_filt=(adapted_rand_error contingency_table variation_of_information) param_dt=(uint8) for shape in "${param_shape[@]}"; do for filt in "${param_filt[@]}"; do for dt in "${param_dt[@]}"; do python cucim_metrics_bench.py -f $filt -i $shape -d $dt -t 4 done done done
0
rapidsai_public_repos/cucim/benchmarks
rapidsai_public_repos/cucim/benchmarks/skimage/cucim_morphology_bench.py
import argparse import copy import functools import math import operator import os import pickle import cupy as cp import numpy as np import pandas as pd import scipy.ndimage as ndi import skimage import skimage.data import skimage.morphology from _image_bench import ImageBench import cucim.skimage import cucim.skimage.morphology class BinaryMorphologyBench(ImageBench): def __init__( self, function_name, shape, footprint=None, dtypes=[bool], fixed_kwargs={}, index_str="", var_kwargs={}, module_cpu=skimage.morphology, module_gpu=cucim.skimage.morphology, run_cpu=True, ): array_kwargs = dict(footprint=footprint) if "footprint" in fixed_kwargs: raise ValueError("fixed_kwargs cannot contain 'footprint'") fixed_kwargs = copy.deepcopy(fixed_kwargs) fixed_kwargs.update(array_kwargs) super().__init__( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, index_str=index_str, module_cpu=module_cpu, module_gpu=module_gpu, run_cpu=run_cpu, ) def set_args(self, dtype): imaged = (cp.random.standard_normal(self.shape) > 0).astype(dtype) image = cp.asnumpy(imaged) self.args_cpu = (image,) self.args_gpu = (imaged,) class IsotropicMorphologyBench(ImageBench): def set_args(self, dtype): imaged = (cp.random.standard_normal(self.shape) > 0).astype(dtype) image = cp.asnumpy(imaged) self.args_cpu = (image,) self.args_gpu = (imaged,) class SkeletonizeBench(ImageBench): def set_args(self, dtype): h = ~skimage.data.horse() nrow = math.ceil(self.shape[0] / h.shape[0]) ncol = math.ceil(self.shape[1] / h.shape[1]) image = np.tile(h, (nrow, ncol))[: self.shape[0], : self.shape[1]] imaged = cp.asarray(image) self.args_cpu = (image,) self.args_gpu = (imaged,) class ReconstructionBench(ImageBench): def set_args(self, dtype): coords = cp.meshgrid( *[cp.linspace(0, 6 * cp.pi, s) for s in self.shape], sparse=True ) bumps = functools.reduce(operator.add, [cp.sin(c) for c in coords]) h = 0.6 seed = bumps - h self.args_cpu = (cp.asnumpy(seed), cp.asnumpy(bumps)) self.args_gpu = (seed, bumps) class RemoveSmallObjectsBench(ImageBench): def _init_test_data(self, dtype): ndim = len(self.shape) if ndim < 2 or ndim > 3: raise ValueError("only 2d and 3d test cases are available") a = cp.array([[0, 0, 0, 1, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 1]], dtype) if ndim == 3: a = a[..., cp.newaxis] a = cp.tile(a, (1, 1, 2)) a = cp.pad(a, ((0, 0), (0, 0), (1, 1)), mode="constant") ntile = [math.ceil(self.shape[i] / a.shape[i]) for i in range(ndim)] a = cp.tile(a, tuple(ntile)) return a[tuple([slice(s) for s in self.shape])] def set_args(self, dtype): a = self._init_test_data(dtype) self.args_cpu = (cp.asnumpy(a), 6) self.args_gpu = (a, 6) class RemoveSmallHolesBench(RemoveSmallObjectsBench): def set_args(self, dtype): a = ~self._init_test_data(dtype) self.args_cpu = (cp.asnumpy(a), 5) self.args_gpu = (a, 5) def main(args): pfile = "cucim_morphology_results.pickle" if os.path.exists(pfile): with open(pfile, "rb") as f: all_results = pickle.load(f) else: all_results = pd.DataFrame() dtypes = [np.dtype(args.dtype)] # image sizes/shapes shape = tuple(list(map(int, (args.img_size.split(","))))) run_cpu = not args.no_cpu for function_name, fixed_kwargs, var_kwargs, allow_color, allow_nd in [ # binary.py ("binary_erosion", dict(), dict(), False, True), ("binary_dilation", dict(), dict(), False, True), ("binary_opening", dict(), dict(), False, True), ("binary_closing", dict(), dict(), False, True), ("isotropic_erosion", dict(), dict(radius=[5, 10, 20]), False, True), ("isotropic_dilation", dict(), dict(radius=[5, 10, 20]), False, True), ("isotropic_opening", dict(), dict(radius=[5, 10, 20]), False, True), ("isotropic_closing", dict(), dict(radius=[5, 10, 20]), False, True), # misc.py ("remove_small_objects", dict(), dict(), False, True), ("remove_small_holes", dict(), dict(), False, True), # gray.py ("erosion", dict(), dict(), False, True), ("dilation", dict(), dict(), False, True), ("opening", dict(), dict(), False, True), ("closing", dict(), dict(), False, True), ("white_tophat", dict(), dict(), False, True), ("black_tophat", dict(), dict(), False, True), # _skeletonize.py ( "medial_axis", dict(random_state=123), dict(return_distance=[False, True]), False, False, ), ("thin", dict(), dict(), False, True), # grayreconstruct.py ("reconstruction", dict(), dict(), False, True), # footprints.py # OMIT the functions from this file (each creates a structuring element) ]: if function_name != args.func_name: continue if not allow_color: if len(shape) > 2 and shape[-1] == 3: continue ndim = len(shape) if function_name in ["thin", "medial_axis"]: if ndim != 2: raise ValueError("only 2d benchmark data has been implemented") if not allow_nd and ndim > 2: continue B = SkeletonizeBench( function_name=function_name, shape=shape, dtypes=[bool], fixed_kwargs={}, var_kwargs=var_kwargs, module_cpu=skimage.morphology, module_gpu=cucim.skimage.morphology, run_cpu=run_cpu, ) if function_name.startswith("binary"): if not allow_nd and ndim > 2: continue for connectivity in range(1, ndim + 1): index_str = f"conn={connectivity}" footprint = ndi.generate_binary_structure(ndim, connectivity) B = BinaryMorphologyBench( function_name=function_name, shape=shape, dtypes=[bool], footprint=footprint, fixed_kwargs={}, var_kwargs=var_kwargs, index_str=index_str, module_cpu=skimage.morphology, module_gpu=cucim.skimage.morphology, run_cpu=run_cpu, ) elif function_name.startswith("isotropic"): if not allow_nd and ndim > 2: continue B = IsotropicMorphologyBench( function_name=function_name, shape=shape, dtypes=[bool], fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.morphology, module_gpu=cucim.skimage.morphology, run_cpu=run_cpu, ) elif function_name in ["remove_small_holes", "remove_small_objects"]: if not allow_nd and ndim > 2: continue if function_name == "remove_small_objects": TestClass = RemoveSmallObjectsBench elif function_name == "remove_small_holes": TestClass = RemoveSmallHolesBench else: raise ValueError(f"unknown function: {function_name}") B = TestClass( function_name=function_name, shape=shape, dtypes=[bool], fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.morphology, module_gpu=cucim.skimage.morphology, run_cpu=run_cpu, ) else: if not allow_nd: if not allow_color: if ndim > 2: continue else: if ndim > 3 or (ndim == 3 and shape[-1] not in [3, 4]): continue if shape[-1] == 3 and not allow_color: continue if function_name == "reconstruction": TestClass = ReconstructionBench else: TestClass = ImageBench B = TestClass( function_name=function_name, shape=shape, dtypes=dtypes, fixed_kwargs=fixed_kwargs, var_kwargs=var_kwargs, module_cpu=skimage.morphology, module_gpu=cucim.skimage.morphology, run_cpu=run_cpu, ) results = B.run_benchmark(duration=args.duration) all_results = pd.concat([all_results, results["full"]]) fbase = os.path.splitext(pfile)[0] all_results.to_csv(fbase + ".csv") all_results.to_pickle(pfile) try: import tabular # noqa: F401 with open(fbase + ".md", "wt") as f: f.write(all_results.to_markdown()) except ImportError: pass if __name__ == "__main__": parser = argparse.ArgumentParser( description="Benchmarking cuCIM morphology functions" ) # fmt: off func_name_choices = [ 'binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing', 'isotropic_erosion', 'isotropic_dilation', 'isotropic_opening', 'isotropic_closing','remove_small_objects', 'remove_small_holes', 'erosion', 'dilation', 'opening', 'closing', 'white_tophat', 'black_tophat', 'thin', 'medial_axis', 'reconstruction' ] # fmt: on dtype_choices = [ "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ] parser.add_argument( "-i", "--img_size", type=str, help=( "Size of input image (omit color channel, it will be appended " "as needed)" ), required=True, ) parser.add_argument( "-d", "--dtype", type=str, help="Dtype of input image", choices=dtype_choices, required=True, ) parser.add_argument( "-f", "--func_name", type=str, help="function to benchmark", choices=func_name_choices, required=True, ) parser.add_argument( "-t", "--duration", type=int, help="time to run benchmark", required=True, ) parser.add_argument( "--no_cpu", action="store_true", help="disable cpu measurements", default=False, ) args = parser.parse_args() main(args)
0
rapidsai_public_repos/cucim
rapidsai_public_repos/cucim/cpp/CMakeLists.txt
# # Copyright (c) 2020-2021, NVIDIA CORPORATION. # 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. # ################################################################################ # Set cmake policy ################################################################################ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.19") cmake_policy(SET CMP0110 NEW) # For add_test() to support arbitrary characters in test name endif() ################################################################################ # Define compile options ################################################################################ if(NOT BUILD_SHARED_LIBS) set(BUILD_SHARED_LIBS ON) endif() ################################################################################ # Set definitions ################################################################################ ################################################################################ # Add library: cucim ################################################################################ add_library(${CUCIM_PACKAGE_NAME} src/core/framework.cpp include/cucim/cuimage.h include/cucim/cache/image_cache.h include/cucim/cache/image_cache_config.h include/cucim/cache/image_cache_manager.h include/cucim/codec/base64.h include/cucim/codec/hash_function.h include/cucim/codec/methods.h include/cucim/concurrent/threadpool.h include/cucim/config/config.h include/cucim/core/framework.h include/cucim/core/plugin.h include/cucim/core/plugin_util.h include/cucim/core/interface.h include/cucim/core/version.h include/cucim/cpp20/find_if.h include/cucim/dynlib/helper.h include/cucim/filesystem/cufile_driver.h include/cucim/filesystem/file_handle.h include/cucim/filesystem/file_path.h include/cucim/io/device.h include/cucim/io/device_type.h include/cucim/io/format/image_format.h include/cucim/loader/batch_data_processor.h include/cucim/loader/thread_batch_data_loader.h include/cucim/loader/tile_info.h include/cucim/logger/logger.h include/cucim/logger/timer.h include/cucim/macros/defines.h include/cucim/memory/dlpack.h include/cucim/memory/memory_manager.h include/cucim/plugin/image_format.h include/cucim/plugin/plugin_config.h include/cucim/profiler/nvtx3.h include/cucim/profiler/profiler.h include/cucim/profiler/profiler_config.h include/cucim/util/cuda.h include/cucim/util/file.h include/cucim/util/platform.h include/cucim/3rdparty/dlpack/dlpack.h include/cucim/3rdparty/dlpack/dlpackcpp.h src/cuimage.cpp src/cache/cache_type.cpp src/cache/image_cache.cpp src/cache/image_cache_config.cpp src/cache/image_cache_empty.h src/cache/image_cache_empty.cpp src/cache/image_cache_manager.cpp src/cache/image_cache_per_process.h src/cache/image_cache_per_process.cpp src/cache/image_cache_shared_memory.h src/cache/image_cache_shared_memory.cpp src/codec/base64.cpp src/concurrent/threadpool.cpp src/config/config.cpp src/core/cucim_framework.h src/core/cucim_framework.cpp src/core/cucim_plugin.h src/core/cucim_plugin.cpp src/core/plugin_manager.h src/core/plugin_manager.cpp src/core/version.inl src/filesystem/cufile_driver.cpp src/filesystem/file_handle.cpp src/io/device.cpp src/io/device_type.cpp src/io/format/image_format.cpp src/loader/batch_data_processor.cpp src/loader/thread_batch_data_loader.cpp src/logger/logger.cpp src/logger/timer.cpp src/memory/memory_manager.cpp src/plugin/image_format.cpp src/plugin/plugin_config.cpp src/profiler/profiler.cpp src/profiler/profiler_config.cpp src/util/file.cpp src/util/platform.cpp) # Compile options set_target_properties(${CUCIM_PACKAGE_NAME} PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO SOVERSION ${PROJECT_VERSION_MAJOR} VERSION ${PROJECT_VERSION} ) # Note: Looks like the following line causes error on CMake 3.18.4 (it is working on 3.18.2). Keeping it for now. set(CUCIM_REQUIRED_FEATURES cxx_std_17) target_compile_features(${CUCIM_PACKAGE_NAME} PRIVATE ${CUCIM_REQUIRED_FEATURES}) # Use generator expression to avoid `nvcc fatal : Value '-std=c++17' is not defined for option 'Werror'` target_compile_options(${CUCIM_PACKAGE_NAME} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-Werror -Wall -Wextra> ) target_compile_definitions(${CUCIM_PACKAGE_NAME} PUBLIC CUCIM_VERSION=${PROJECT_VERSION} CUCIM_VERSION_MAJOR=${PROJECT_VERSION_MAJOR} CUCIM_VERSION_MINOR=${PROJECT_VERSION_MINOR} CUCIM_VERSION_PATCH=${PROJECT_VERSION_PATCH} CUCIM_VERSION_BUILD=${PROJECT_VERSION_BUILD} CUCIM_SUPPORT_GDS=$<BOOL:${CUCIM_SUPPORT_GDS}> CUCIM_STATIC_GDS=$<BOOL:${CUCIM_STATIC_GDS}> CUCIM_SUPPORT_CUDA=$<BOOL:${CUCIM_SUPPORT_CUDA}> CUCIM_SUPPORT_NVTX=$<BOOL:${CUCIM_SUPPORT_NVTX}> _GLIBCXX_USE_CXX11_ABI=0 # TODO: create two library, one with CXX11 ABI and one without it. ) # Link libraries target_link_libraries(${CUCIM_PACKAGE_NAME} PUBLIC ${CMAKE_DL_LIBS} Threads::Threads # -lpthread $<BUILD_INTERFACE:deps::fmt> $<INSTALL_INTERFACE:cucim::fmt-header-only> PRIVATE CUDA::cudart deps::abseil deps::gds deps::libcuckoo deps::boost-header-only deps::json deps::nvtx3 deps::taskflow ) if (CUCIM_STATIC_GDS) target_link_libraries(${CUCIM_PACKAGE_NAME} PUBLIC CUDA::cuda_driver # this may not be needed $<BUILD_INTERFACE:deps::gds_static> ) endif () target_include_directories(${CUCIM_PACKAGE_NAME} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/${CUCIM_PACKAGE_NAME}/3rdparty> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/${CUCIM_PACKAGE_NAME}/3rdparty> # for 3rdparty libraries such as dlpack, nvtx3, and fmt PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src ) add_library(${CUCIM_PACKAGE_NAME}::${CUCIM_PACKAGE_NAME} ALIAS ${CUCIM_PACKAGE_NAME}) ################################################################################ # Add library: cucim-header-only ################################################################################ add_library(${CUCIM_PACKAGE_NAME}-header-only INTERFACE) target_compile_definitions(${CUCIM_PACKAGE_NAME}-header-only INTERFACE CUCIM_VERSION=${PROJECT_VERSION} CUCIM_VERSION_MAJOR=${PROJECT_VERSION_MAJOR} CUCIM_VERSION_MINOR=${PROJECT_VERSION_MINOR} CUCIM_VERSION_PATCH=${PROJECT_VERSION_PATCH} CUCIM_VERSION_BUILD=${PROJECT_VERSION_BUILD} CUCIM_SUPPORT_GDS=$<BOOL:${CUCIM_SUPPORT_GDS}> CUCIM_STATIC_GDS=$<BOOL:${CUCIM_STATIC_GDS}> CUCIM_SUPPORT_CUDA=$<BOOL:${CUCIM_SUPPORT_CUDA}> CUCIM_SUPPORT_NVTX=$<BOOL:${CUCIM_SUPPORT_NVTX}> CUCIM_HEADER_ONLY=1 ) target_compile_features(${CUCIM_PACKAGE_NAME}-header-only INTERFACE ${CUCIM_REQUIRED_FEATURES}) target_include_directories(${CUCIM_PACKAGE_NAME}-header-only INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/${CUCIM_PACKAGE_NAME}/3rdparty> ) add_library(${CUCIM_PACKAGE_NAME}::${CUCIM_PACKAGE_NAME}-header-only ALIAS ${CUCIM_PACKAGE_NAME}-header-only) ################################################################################ # Add tests ################################################################################ add_subdirectory(tests) ################################################################################# ## Add bindings ################################################################################# #add_subdirectory(bindings/python) unset(BUILD_SHARED_LIBS CACHE)
0
rapidsai_public_repos/cucim/cpp/include
rapidsai_public_repos/cucim/cpp/include/cucim/cuimage.h
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_CUIMAGE_H #define CUCIM_CUIMAGE_H #include "cucim/core/framework.h" #include "cucim/cache/image_cache_manager.h" #include "cucim/config/config.h" #include "cucim/filesystem/file_path.h" #include "cucim/io/device.h" #include "cucim/io/format/image_format.h" #include "cucim/loader/thread_batch_data_loader.h" #include "cucim/memory/dlpack.h" #include "cucim/plugin/image_format.h" #include "cucim/profiler/profiler.h" #include <array> #include <cstddef> // for std::ptrdiff_t #include <iterator> // for std::forward_iterator_tag #include <memory> #include <mutex> #include <set> #include <string> #include <vector> // Forward declarations for DLDataType's equality operator. template <> struct std::hash<DLDataType>; EXPORT_VISIBLE bool operator==(const DLDataType& lhs, const DLDataType& rhs); EXPORT_VISIBLE bool operator!=(const DLDataType& lhs, const DLDataType& rhs); namespace cucim { // Forward declarations class CuImage; template <typename DataType> class CuImageIterator; using DetectedFormat = std::pair<std::string, std::vector<std::string>>; using Metadata = std::string; using Shape = std::vector<int64_t>; constexpr int64_t kWholeRange = -1; /** * * This class is used in both cases: * 1. Specifying index for dimension string (e.g., "YXC" => Y:0, X:1, C:2) * 2. Specifying index for read_region() (e.g., {{'C', -1}, {'T', 0}} => C:(whole range), T:0) */ class EXPORT_VISIBLE DimIndices { public: DimIndices(const char* dims = nullptr); DimIndices(std::vector<std::pair<char, int64_t>> init_list); int64_t index(char dim_char) const; private: io::format::DimIndicesDesc dim_indices_{ { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } }; }; class EXPORT_VISIBLE ResolutionInfo { public: ResolutionInfo(io::format::ResolutionInfoDesc desc); uint16_t level_count() const; const std::vector<int64_t>& level_dimensions() const; std::vector<int64_t> level_dimension(uint16_t level) const; const std::vector<float>& level_downsamples() const; float level_downsample(uint16_t level) const; const std::vector<uint32_t>& level_tile_sizes() const; std::vector<uint32_t> level_tile_size(uint16_t level) const; private: uint16_t level_count_; uint16_t level_ndim_; std::vector<int64_t> level_dimensions_; std::vector<float> level_downsamples_; std::vector<uint32_t> level_tile_sizes_; }; /** * Detect available formats (plugins) from the input path. * * The plugin name can be used later to specify the plugin to load the image file explicitly. * * @param path An input path to detect available formats * @return A tuple that describes the format (file format or format vendor) and the list of plugin names that * supports the file */ DetectedFormat detect_format(filesystem::Path path); class EXPORT_VISIBLE CuImage : public std::enable_shared_from_this<CuImage> { public: CuImage(const filesystem::Path& path); CuImage(const filesystem::Path& path, const std::string& plugin_name); CuImage(const CuImage& cuimg) = delete; CuImage(CuImage&& cuimg); CuImage(const CuImage* cuimg, io::format::ImageMetadataDesc* image_metadata, cucim::io::format::ImageDataDesc* image_data); ~CuImage(); operator bool() const { return !!image_format_ && !is_loaded_; } static Framework* get_framework(); static config::Config* get_config(); static std::shared_ptr<profiler::Profiler> profiler(); static std::shared_ptr<profiler::Profiler> profiler(profiler::ProfilerConfig& config); static cache::ImageCacheManager& cache_manager(); static std::shared_ptr<cache::ImageCache> cache(); static std::shared_ptr<cache::ImageCache> cache(cache::ImageCacheConfig& config); static bool is_trace_enabled(); filesystem::Path path() const; bool is_loaded() const; io::Device device() const; Metadata raw_metadata() const; Metadata metadata() const; uint16_t ndim() const; std::string dims() const; Shape shape() const; std::vector<int64_t> size(std::string dim_order = std::string{}) const; DLDataType dtype() const; std::string typestr() const; std::vector<std::string> channel_names() const; std::vector<float> spacing(std::string dim_order = std::string{}) const; std::vector<std::string> spacing_units(std::string dim_order = std::string{}) const; std::array<float, 3> origin() const; std::array<std::array<float, 3>, 3> direction() const; std::string coord_sys() const; ResolutionInfo resolutions() const; loader::ThreadBatchDataLoader* loader() const; memory::DLTContainer container() const; CuImage read_region(std::vector<int64_t>&& location, std::vector<int64_t>&& size, uint16_t level = 0, uint32_t num_workers = 0, uint32_t batch_size = 1, bool drop_last = false, uint32_t prefetch_factor = 2, bool shuffle = false, uint64_t seed = 0, const DimIndices& region_dim_indices = {}, const io::Device& device = "cpu", DLTensor* buf = nullptr, const std::string& shm_name = std::string{}) const; std::set<std::string> associated_images() const; CuImage associated_image(const std::string& name, const io::Device& device = "cpu") const; void save(std::string file_path) const; void close(); ///////////////////////////// // Iterator implementation // ///////////////////////////// using iterator = CuImageIterator<CuImage>; using const_iterator = CuImageIterator<const CuImage>; friend class CuImageIterator<CuImage>; friend class CuImageIterator<const CuImage>; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; private: using Mutex = std::mutex; using ScopedLock = std::scoped_lock<Mutex>; explicit CuImage(); void ensure_init(); bool crop_image(const io::format::ImageReaderRegionRequestDesc& request, io::format::ImageDataDesc& out_image_data) const; static Framework* framework_; // Note: config_ should be placed before cache_manager_ and profiler_ (those depend on config_) static std::unique_ptr<config::Config> config_; static std::shared_ptr<profiler::Profiler> profiler_; static std::unique_ptr<cache::ImageCacheManager> cache_manager_; static std::unique_ptr<cucim::plugin::ImageFormat> image_format_plugins_; mutable Mutex mutex_; cucim::io::format::ImageFormatDesc* image_format_ = nullptr; std::shared_ptr<CuCIMFileHandle> file_handle_; io::format::ImageMetadataDesc* image_metadata_ = nullptr; io::format::ImageDataDesc* image_data_ = nullptr; bool is_loaded_ = false; DimIndices dim_indices_{}; std::set<std::string> associated_images_; }; template <typename DataType> class EXPORT_VISIBLE CuImageIterator { public: using iterator_category = std::forward_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = DataType; using pointer = value_type*; using reference = std::shared_ptr<value_type>; CuImageIterator(std::shared_ptr<DataType> cuimg, bool ending = false); CuImageIterator(const CuImageIterator<DataType>& it) = default; reference operator*() const; pointer operator->(); CuImageIterator<DataType>& operator++(); CuImageIterator<DataType> operator++(int); bool operator==(const CuImageIterator<DataType>& other); bool operator!=(const CuImageIterator<DataType>& other); int64_t index(); /// batch index uint64_t size() const; /// number of batches private: void increase_index_(); std::shared_ptr<DataType> cuimg_; void* loader_ = nullptr; int64_t batch_index_ = 0; uint64_t total_batch_count_ = 0; }; template class CuImageIterator<CuImage>; template class CuImageIterator<const CuImage>; } // namespace cucim #endif // CUCIM_CUIMAGE_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/util/cuda.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ // #ifndef CUCIM_UTIL_CUDA_H #define CUCIM_UTIL_CUDA_H #if CUCIM_SUPPORT_CUDA # include <cuda_runtime.h> #endif #define CUDA_TRY(stmt) \ { \ cuda_status = stmt; \ if (cudaSuccess != cuda_status) \ { \ fmt::print(stderr, "[Error] CUDA Runtime call {} in line {} of file {} failed with '{}' ({}).\n", #stmt, \ __LINE__, __FILE__, cudaGetErrorString(cuda_status), cuda_status); \ } \ } #define CUDA_ERROR(stmt) \ { \ cuda_status = stmt; \ if (cudaSuccess != cuda_status) \ { \ throw std::runtime_error( \ fmt::format("[Error] CUDA Runtime call {} in line {} of file {} failed with '{}' ({}).\n", #stmt, \ __LINE__, __FILE__, cudaGetErrorString(cuda_status), cuda_status)); \ } \ } #define NVJPEG_TRY(stmt) \ { \ nvjpegStatus_t _nvjpeg_status = stmt; \ if (_nvjpeg_status != NVJPEG_STATUS_SUCCESS) \ { \ fmt::print("[Error] NVJPEG call {} in line {} of file {} failed with the error code {}.\n", #stmt, \ __LINE__, __FILE__, _nvjpeg_status)); \ } \ } #define NVJPEG_ERROR(stmt) \ { \ nvjpegStatus_t _nvjpeg_status = stmt; \ if (_nvjpeg_status != NVJPEG_STATUS_SUCCESS) \ { \ throw std::runtime_error( \ fmt::format("[Error] NVJPEG call {} in line {} of file {} failed with the error code {}.\n", #stmt, \ __LINE__, __FILE__, _nvjpeg_status)); \ } \ } namespace cucim::util { } // namespace cucim::util #endif // CUCIM_UTIL_CUDA_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/util/platform.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ // #ifndef CUCIM_UTIL_PLATFORM_H #define CUCIM_UTIL_PLATFORM_H #include "cucim/macros/api_header.h" /** * @brief Platform-specific macros and functions. */ namespace cucim::util { EXPORT_VISIBLE bool is_in_wsl(); } // namespace cucim::util #endif // CUCIM_UTIL_PLATFORM_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/util/file.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ // #ifndef CUCIM_UTIL_FILE_H #define CUCIM_UTIL_FILE_H #include "cucim/core/framework.h" /** * @brief Utility methods that need to be refactored later. */ namespace cucim::util { EXPORT_VISIBLE bool file_exists(const char* path); } // namespace cucim::util #endif // CUCIM_UTIL_FILE_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/config/config.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_CONFIG_CONFIG_H #define CUCIM_CONFIG_CONFIG_H #include "cucim/macros/api_header.h" #include "cucim/cache/cache_type.h" #include "cucim/cache/image_cache_config.h" #include "cucim/plugin/plugin_config.h" #include "cucim/profiler/profiler_config.h" #include <string> #include <string_view> #include <sys/types.h> #include <unistd.h> namespace cucim::config { constexpr const char* kDefaultConfigFileName = ".cucim.json"; class EXPORT_VISIBLE Config { public: Config(); cucim::cache::ImageCacheConfig& cache(); cucim::plugin::PluginConfig& plugin(); cucim::profiler::ProfilerConfig& profiler(); std::string shm_name() const; pid_t pid() const; pid_t ppid() const; pid_t pgid() const; private: std::string get_config_path() const; bool parse_config(std::string& path); void set_default_configuration(); void override_from_envs(); void init_configs(); std::string source_path_; cucim::cache::ImageCacheConfig cache_; cucim::plugin::PluginConfig plugin_; cucim::profiler::ProfilerConfig profiler_; }; } // namespace cucim::config #endif // CUCIM_CONFIG_CONFIG_H
0
rapidsai_public_repos/cucim/cpp/include/cucim/3rdparty
rapidsai_public_repos/cucim/cpp/include/cucim/3rdparty/dlpack/dlpack.h
// From https://github.com/dmlc/dlpack/blob/v0.6/include/dlpack/dlpack.h // clang-format off /*! * Copyright (c) 2017 by Contributors * \file dlpack.h * \brief The common header of DLPack. */ #ifndef DLPACK_DLPACK_H_ #define DLPACK_DLPACK_H_ #ifdef __cplusplus #define DLPACK_EXTERN_C extern "C" #else #define DLPACK_EXTERN_C #endif /*! \brief The current version of dlpack */ #define DLPACK_VERSION 60 /*! \brief DLPACK_DLL prefix for windows */ #ifdef _WIN32 #ifdef DLPACK_EXPORTS #define DLPACK_DLL __declspec(dllexport) #else #define DLPACK_DLL __declspec(dllimport) #endif #else #define DLPACK_DLL #endif #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /*! * \brief The device type in DLDevice. */ typedef enum { /*! \brief CPU device */ kDLCPU = 1, /*! \brief CUDA GPU device */ kDLCUDA = 2, /*! * \brief Pinned CUDA CPU memory by cudaMallocHost */ kDLCUDAHost = 3, /*! \brief OpenCL devices. */ kDLOpenCL = 4, /*! \brief Vulkan buffer for next generation graphics. */ kDLVulkan = 7, /*! \brief Metal for Apple GPU. */ kDLMetal = 8, /*! \brief Verilog simulator buffer */ kDLVPI = 9, /*! \brief ROCm GPUs for AMD GPUs */ kDLROCM = 10, /*! * \brief Pinned ROCm CPU memory allocated by hipMallocHost */ kDLROCMHost = 11, /*! * \brief Reserved extension device type, * used for quickly test extension device * The semantics can differ depending on the implementation. */ kDLExtDev = 12, /*! * \brief CUDA managed/unified memory allocated by cudaMallocManaged */ kDLCUDAManaged = 13, } DLDeviceType; /*! * \brief A Device for Tensor and operator. */ typedef struct { /*! \brief The device type used in the device. */ DLDeviceType device_type; /*! * \brief The device index. * For vanilla CPU memory, pinned memory, or managed memory, this is set to 0. */ int device_id; } DLDevice; /*! * \brief The type code options DLDataType. */ typedef enum { /*! \brief signed integer */ kDLInt = 0U, /*! \brief unsigned integer */ kDLUInt = 1U, /*! \brief IEEE floating point */ kDLFloat = 2U, /*! * \brief Opaque handle type, reserved for testing purposes. * Frameworks need to agree on the handle data type for the exchange to be well-defined. */ kDLOpaqueHandle = 3U, /*! \brief bfloat16 */ kDLBfloat = 4U, /*! * \brief complex number * (C/C++/Python layout: compact struct per complex number) */ kDLComplex = 5U, } DLDataTypeCode; /*! * \brief The data type the tensor can hold. * * Examples * - float: type_code = 2, bits = 32, lanes=1 * - float4(vectorized 4 float): type_code = 2, bits = 32, lanes=4 * - int8: type_code = 0, bits = 8, lanes=1 * - std::complex<float>: type_code = 5, bits = 64, lanes = 1 */ typedef struct { /*! * \brief Type code of base types. * We keep it uint8_t instead of DLDataTypeCode for minimal memory * footprint, but the value should be one of DLDataTypeCode enum values. * */ uint8_t code; /*! * \brief Number of bits, common choices are 8, 16, 32. */ uint8_t bits; /*! \brief Number of lanes in the type, used for vector types. */ uint16_t lanes; } DLDataType; /*! * \brief Plain C Tensor object, does not manage memory. */ typedef struct { /*! * \brief The opaque data pointer points to the allocated data. This will be * CUDA device pointer or cl_mem handle in OpenCL. This pointer is always * aligned to 256 bytes as in CUDA. * * For given DLTensor, the size of memory required to store the contents of * data is calculated as follows: * * \code{.c} * static inline size_t GetDataSize(const DLTensor* t) { * size_t size = 1; * for (tvm_index_t i = 0; i < t->ndim; ++i) { * size *= t->shape[i]; * } * size *= (t->dtype.bits * t->dtype.lanes + 7) / 8; * return size; * } * \endcode */ void* data; /*! \brief The device of the tensor */ DLDevice device; /*! \brief Number of dimensions */ int ndim; /*! \brief The data type of the pointer*/ DLDataType dtype; /*! \brief The shape of the tensor */ int64_t* shape; /*! * \brief strides of the tensor (in number of elements, not bytes) * can be NULL, indicating tensor is compact and row-majored. */ int64_t* strides; /*! \brief The offset in bytes to the beginning pointer to data */ uint64_t byte_offset; } DLTensor; /*! * \brief C Tensor object, manage memory of DLTensor. This data structure is * intended to facilitate the borrowing of DLTensor by another framework. It is * not meant to transfer the tensor. When the borrowing framework doesn't need * the tensor, it should call the deleter to notify the host that the resource * is no longer needed. */ typedef struct DLManagedTensor { /*! \brief DLTensor which is being memory managed */ DLTensor dl_tensor; /*! \brief the context of the original host framework of DLManagedTensor in * which DLManagedTensor is used in the framework. It can also be NULL. */ void * manager_ctx; /*! \brief Destructor signature void (*)(void*) - this should be called * to destruct manager_ctx which holds the DLManagedTensor. It can be NULL * if there is no way for the caller to provide a reasonable destructor. * The destructors deletes the argument self as well. */ void (*deleter)(struct DLManagedTensor * self); } DLManagedTensor; #ifdef __cplusplus } // DLPACK_EXTERN_C #endif #endif // DLPACK_DLPACK_H_ // clang-format on
0
rapidsai_public_repos/cucim/cpp/include/cucim/3rdparty
rapidsai_public_repos/cucim/cpp/include/cucim/3rdparty/dlpack/dlpackcpp.h
// From https://github.com/dmlc/dlpack/blob/v0.6/contrib/dlpack/dlpackcpp.h // clang-format off /*! * Copyright (c) 2017 by Contributors * \file dlpackcpp.h * \brief Example C++ wrapper of DLPack */ #ifndef DLPACK_DLPACKCPP_H_ #define DLPACK_DLPACKCPP_H_ #include <dlpack/dlpack.h> #include <cstdint> // for int64_t etc #include <cstdlib> // for free() #include <functional> // for std::multiplies #include <memory> #include <numeric> #include <vector> namespace dlpack { // Example container wrapping of DLTensor. class DLTContainer { public: DLTContainer() { // default to float32 handle_.data = nullptr; handle_.dtype.code = kDLFloat; handle_.dtype.bits = 32U; handle_.dtype.lanes = 1U; handle_.device.device_type = kDLCPU; handle_.device.device_id = 0; handle_.shape = nullptr; handle_.strides = nullptr; handle_.byte_offset = 0; } ~DLTContainer() { if (origin_ == nullptr) { free(handle_.data); } } operator DLTensor() { return handle_; } operator DLTensor*() { return &(handle_); } void Reshape(const std::vector<int64_t>& shape) { shape_ = shape; int64_t sz = std::accumulate(std::begin(shape), std::end(shape), int64_t(1), std::multiplies<int64_t>()); int ret = posix_memalign(&handle_.data, 256, sz); if (ret != 0) throw std::bad_alloc(); handle_.shape = &shape_[0]; handle_.ndim = static_cast<uint32_t>(shape.size()); } private: DLTensor handle_; std::vector<int64_t> shape_; std::vector<int64_t> strides_; // original space container, if std::shared_ptr<DLTContainer> origin_; }; } // namespace dlpack #endif // DLPACK_DLPACKCPP_H_ // clang-format on
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/dynlib/helper.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_DYNAMIC_LIBRARY_H #define CUCIM_DYNAMIC_LIBRARY_H // Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "../macros/defines.h" #include <string> #include <vector> #if CUCIM_PLATFORM_LINUX # include <dlfcn.h> #else # error "This platform is not supported!" #endif namespace cucim { namespace dynlib { #if CUCIM_PLATFORM_LINUX using LibraryHandle = void*; #else # error "This platform is not supported!" #endif template <typename T> T get_library_symbol(LibraryHandle libHandle, const char* name) { #if CUCIM_PLATFORM_LINUX return reinterpret_cast<T>(::dlsym(libHandle, name)); #else # error "This platform is not supported!" #endif } inline LibraryHandle load_library(const char* library_name, int mode = -1) { #if CUCIM_PLATFORM_LINUX if (mode == -1) { return dlopen(library_name, RTLD_LAZY); } else { return dlopen(library_name, mode); } #else # error "This platform is not supported!" #endif } inline LibraryHandle load_library(const std::vector<const char*>& names, int mode = -1) { #if CUCIM_PLATFORM_LINUX LibraryHandle handle_ = nullptr; for (const char* name : names) { handle_= load_library(name, mode); if (handle_ != nullptr) { return handle_; } } return nullptr; #else # error "This platform is not supported!" #endif } inline std::string get_last_load_library_error() { #if CUCIM_PLATFORM_LINUX return dlerror(); #else # error "This platform is not supported!" #endif } inline void unload_library(LibraryHandle library_handle) { if (library_handle) { #if CUCIM_PLATFORM_LINUX ::dlclose(library_handle); #else # error "This platform is not supported!" #endif } } } // namespace dynlib } // namespace cucim #endif // CUCIM_DYNAMIC_LIBRARY_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/cache/image_cache_config.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_CACHE_IMAGE_CACHE_CONFIG_H #define CUCIM_CACHE_IMAGE_CACHE_CONFIG_H #include "cucim/core/framework.h" #include "cucim/cache/cache_type.h" namespace cucim::cache { constexpr uint64_t kOneMiB = 1024UL * 1024; constexpr std::string_view kDefaultCacheTypeStr = "nocache"; constexpr CacheType kDefaultCacheType = cucim::cache::CacheType::kNoCache; constexpr uint64_t kDefaultCacheMemoryCapacity = 1024UL; /** * @brief Mutex Pool size * * >>> from functools import reduce * >>> def calc(pool_size, thread_size): * >>> a = reduce(lambda x,y: x*y, range(pool_size, pool_size - thread_size, -1)) * >>> print(1 - (a / (pool_size**thread_size))) * * >>> calc(100003, 128) * 0.07809410393222294 * >>> calc(100003, 256) * 0.2786772006302005 * * See https://godbolt.org/z/Tvx8179xK * Creating a pool of 100000 mutexes takes only about 4 MB which is not big. * I believe that making the mutex size biggger enough helps to the reduce the thread contention. * For systems with more than 256 threads, the pool size should be larger. * Choose a prime number for the pool size (https://primes.utm.edu/lists/small/100000.txt). */ constexpr uint32_t kDefaultCacheMutexPoolCapacity = 100003; constexpr uint32_t kDefaultCacheListPadding = 10000; constexpr uint32_t kDefaultCacheExtraSharedMemorySize = 100; constexpr bool kDefaultCacheRecordStat = false; // Assume that user uses memory block whose size is least 256 x 256 x 3 bytes. constexpr uint32_t calc_default_cache_capacity(uint64_t memory_capacity_in_bytes) { return memory_capacity_in_bytes / (256UL * 256 * 3); } struct EXPORT_VISIBLE ImageCacheConfig { void load_config(const void* json_obj); CacheType type = CacheType::kNoCache; uint32_t memory_capacity = kDefaultCacheMemoryCapacity; uint32_t capacity = calc_default_cache_capacity(kOneMiB * kDefaultCacheMemoryCapacity); uint32_t mutex_pool_capacity = kDefaultCacheMutexPoolCapacity; uint32_t list_padding = kDefaultCacheListPadding; uint32_t extra_shared_memory_size = kDefaultCacheExtraSharedMemorySize; bool record_stat = kDefaultCacheRecordStat; }; } // namespace cucim::cache #endif // CUCIM_CACHE_IMAGE_CACHE_CONFIG_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/cache/image_cache.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_CACHE_IMAGE_CACHE_H #define CUCIM_CACHE_IMAGE_CACHE_H #include "cucim/core/framework.h" #include "cucim/cache/cache_type.h" #include "cucim/cache/image_cache_config.h" #include <memory> #include <atomic> #include <functional> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> namespace cucim::cache { struct EXPORT_VISIBLE ImageCacheKey { ImageCacheKey(uint64_t file_hash, uint64_t index); uint64_t file_hash = 0; /// st_dev + st_ino + st_mtime + ifd_index uint64_t location_hash = 0; /// tile_index or (x , y) }; struct EXPORT_VISIBLE ImageCacheValue { ImageCacheValue(void* data, uint64_t size, void* user_obj = nullptr, const cucim::io::DeviceType device_type = cucim::io::DeviceType::kCPU); virtual ~ImageCacheValue(){}; operator bool() const; void* data = nullptr; uint64_t size = 0; void* user_obj = nullptr; cucim::io::DeviceType device_type = cucim::io::DeviceType::kCPU; }; /** * @brief Image Cache for loading tiles. * * FIFO is used for cache replacement policy here. * */ class EXPORT_VISIBLE ImageCache : public std::enable_shared_from_this<ImageCache> { public: ImageCache(const ImageCacheConfig& config, CacheType type = CacheType::kNoCache, const cucim::io::DeviceType device_type = cucim::io::DeviceType::kCPU); virtual ~ImageCache(){}; virtual CacheType type() const; virtual const char* type_str() const; virtual cucim::io::DeviceType device_type() const; virtual ImageCacheConfig& config(); virtual ImageCacheConfig get_config() const; /** * @brief Create a key object for the image cache. * * @param file_hash An hash value used for a specific file. * @param index An hash value to locate a specific index/coordination in the image. * @return std::shared_ptr<ImageCacheKey> A shared pointer containing %ImageCacheKey. */ virtual std::shared_ptr<ImageCacheKey> create_key(uint64_t file_hash, uint64_t index) = 0; virtual std::shared_ptr<ImageCacheValue> create_value( void* data, uint64_t size, const cucim::io::DeviceType device_type = cucim::io::DeviceType::kCPU) = 0; virtual void* allocate(std::size_t n) = 0; virtual void lock(uint64_t index) = 0; virtual void unlock(uint64_t index) = 0; virtual void* mutex(uint64_t index) = 0; virtual bool insert(std::shared_ptr<ImageCacheKey>& key, std::shared_ptr<ImageCacheValue>& value) = 0; virtual void remove_front() = 0; virtual uint32_t size() const = 0; virtual uint64_t memory_size() const = 0; virtual uint32_t capacity() const = 0; virtual uint64_t memory_capacity() const = 0; virtual uint64_t free_memory() const = 0; /** * @brief Record cache stat. * * Stat values would be reset with this method. * * @param value Whether if cache stat would be recorded or not */ virtual void record(bool value) = 0; /** * @brief Return whether if cache stat is recorded or not * * @return true if cache stat is recorded. false otherwise */ virtual bool record() const = 0; virtual uint64_t hit_count() const = 0; virtual uint64_t miss_count() const = 0; /** * @brief Attempt to preallocate enough memory for specified number of elements and memory size. * * This method is not thread-safe. * * @param capacity Number of elements required * @param memory_capacity Size of memory required in bytes */ virtual void reserve(const ImageCacheConfig& config) = 0; virtual std::shared_ptr<ImageCacheValue> find(const std::shared_ptr<ImageCacheKey>& key) = 0; protected: CacheType type_ = CacheType::kNoCache; cucim::io::DeviceType device_type_ = cucim::io::DeviceType::kCPU; ImageCacheConfig config_; }; } // namespace cucim::cache #endif // CUCIM_CACHE_IMAGE_CACHE_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/cache/image_cache_manager.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_CACHE_IMAGE_CACHE_MANAGER_H #define CUCIM_CACHE_IMAGE_CACHE_MANAGER_H #include "cucim/core/framework.h" #include "cucim/cache/image_cache.h" #include "cucim/io/device_type.h" namespace cucim::cache { constexpr uint32_t kDefaultTileSize = 256; constexpr uint32_t kDefaultPatchSize = 256; uint32_t EXPORT_VISIBLE preferred_memory_capacity(const std::vector<uint64_t>& image_size, const std::vector<uint32_t>& tile_size, const std::vector<uint32_t>& patch_size, uint32_t bytes_per_pixel = 3); class EXPORT_VISIBLE ImageCacheManager { public: ImageCacheManager(); ImageCache& cache() const; std::shared_ptr<ImageCache> cache(const ImageCacheConfig& config); std::shared_ptr<ImageCache> get_cache() const; void reserve(uint32_t new_memory_capacity); void reserve(uint32_t new_memory_capacity, uint32_t new_capacity); static std::unique_ptr<ImageCache> create_cache(const ImageCacheConfig& cache_config, const cucim::io::DeviceType device_type = cucim::io::DeviceType::kCPU); private: std::unique_ptr<ImageCache> create_cache() const; std::shared_ptr<ImageCache> cache_; }; } // namespace cucim::cache #endif // CUCIM_CACHE_IMAGE_CACHE_MANAGER_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/cache/cache_type.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_CACHE_CACHE_TYPE_H #define CUCIM_CACHE_CACHE_TYPE_H #include "cucim/macros/api_header.h" #include <array> #include <cstdint> #include <string_view> namespace cucim::cache { constexpr std::size_t kCacheTypeCount = 3; enum class CacheType : uint8_t { kNoCache, kPerProcess, kSharedMemory }; // Using constexpr map (https://www.youtube.com/watch?v=INn3xa4pMfg) struct CacheTypeMap { std::array<std::pair<std::string_view, CacheType>, kCacheTypeCount> data; [[nodiscard]] constexpr CacheType at(const std::string_view& key) const; }; EXPORT_VISIBLE CacheType lookup_cache_type(const std::string_view sv); struct CacheTypeStrMap { std::array<std::pair<CacheType, std::string_view>, kCacheTypeCount> data; [[nodiscard]] constexpr std::string_view at(const CacheType& key) const; }; EXPORT_VISIBLE std::string_view lookup_cache_type_str(const CacheType type); } // namespace cucim::cache #endif // CUCIM_CACHE_CACHE_TYPE_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/logger/logger.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_LOGGER_H #define CUCIM_LOGGER_H #endif // CUCIM_LOGGER_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/logger/timer.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_TIMER_H #define CUCIM_TIMER_H #include "cucim/macros/defines.h" #include <chrono> namespace cucim::logger { class EXPORT_VISIBLE Timer { public: Timer(const char* message, bool auto_start = true, bool auto_output = true); void start(); double stop(); double elapsed_time(); void print(const char* message = nullptr); ~Timer(); private: const char* message_ = nullptr; bool is_auto_output_ = false; double elapsed_seconds_ = -1; std::chrono::time_point<std::chrono::system_clock> start_{}; std::chrono::time_point<std::chrono::system_clock> end_{}; }; } // namespace cucim::logger #endif // CUCIM_TIMER_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/core/interface.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_INTERFACE_H #define CUCIM_INTERFACE_H #include "cucim/core/version.h" namespace cucim { struct InterfaceDesc { const char* name = nullptr; InterfaceVersion version = { 0, 1 }; }; /** * Macro to declare a plugin interface. */ #define CUCIM_PLUGIN_INTERFACE(name, major, minor) \ static cucim::InterfaceDesc get_interface_desc() \ { \ return cucim::InterfaceDesc{ name, { major, minor } }; \ } } // namespace cucim #include "../macros/defines.h" #endif // CUCIM_INTERFACE_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/core/framework.h
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_FRAMEWORK_H #define CUCIM_FRAMEWORK_H #include "cucim/core/plugin.h" #include <cstdlib> #include "cucim/memory/memory_manager.h" #define CUCIM_FRAMEWORK_GLOBALS(client_name) \ CUCIM_NO_EXPORT const char* g_cucim_client_name = client_name; \ CUCIM_NO_EXPORT cucim::Framework* g_cucim_framework = nullptr; namespace cucim { #define TEMP_STR(x) #x #define TEMP_XSTR(x) TEMP_STR(x) const struct Version kFrameworkVersion = { static_cast<uint32_t>(std::atoi(TEMP_XSTR(CUCIM_VERSION_MAJOR))), static_cast<uint32_t>(std::atoi(TEMP_XSTR(CUCIM_VERSION_MINOR))), static_cast<uint32_t>(std::atoi(TEMP_XSTR(CUCIM_VERSION_PATCH))) }; #undef TEMP_STR #undef TEMP_XSTR struct PluginRegistrationDesc { OnPluginRegisterFn on_register; ///< Required // OnPluginStartupFn on_startup_fn; ///! Can be nullptr // OnPluginShutdownFn on_shutdown_fn; ///! Can be nullptr OnGetPluginDepsFn on_get_deps; ///! Can be nullptr // OnReloadDependencyFn on_reload_dependency_fn; ///! Can be nullptr // OnPluginPreStartupFn on_pre_startup_fn; ///! Can be nullptr // OnPluginPostShutdownFn on_post_shutdown_fn; ///! Can be nullptr }; struct PluginLoadingDesc { const char* plugin_path; static PluginLoadingDesc get_default() { static constexpr const char* default_plugin_path = "[email protected]"; return { default_plugin_path }; } }; struct Framework { // TODO: need to update for better plugin support - https://github.com/rapidsai/cucim/issues/134 // void load_plugins(const PluginLoadingDesc& desc = PluginLoadingDesc::get_default()); bool(CUCIM_ABI* register_plugin)(const char* client_name, const PluginRegistrationDesc& desc); void*(CUCIM_ABI* acquire_interface_from_library_with_client)(const char* client_name, InterfaceDesc desc, const char* library_path); void(CUCIM_ABI* unload_all_plugins)(); template <typename T> T* acquire_interface_from_library(const char* library_path); // cuCIM-specific methods void(CUCIM_ABI* load_plugin)(const char* library_path); const char*(CUCIM_ABI* get_plugin_root)(); void(CUCIM_ABI* set_plugin_root)(const char* path); }; CUCIM_API cucim::Framework* acquire_framework(const char* app_name, Version framework_version = kFrameworkVersion); CUCIM_API void release_framework(); } // namespace cucim extern const char* g_cucim_client_name; extern cucim::Framework* g_cucim_framework; namespace cucim { inline Framework* get_framework() { return g_cucim_framework; } template <typename T> T* Framework::acquire_interface_from_library(const char* library_path) { const auto desc = T::get_interface_desc(); return static_cast<T*>(this->acquire_interface_from_library_with_client(g_cucim_client_name, desc, library_path)); } } // namespace cucim #endif // CUCIM_FRAMEWORK_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/core/version.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_VERSION_H #define CUCIM_VERSION_H #include <cstdint> #ifndef CUCIM_VERSION_MAJOR # error "CUCIM_VERSION_MAJOR is not defined" #endif #ifndef CUCIM_VERSION_MINOR # error "CUCIM_VERSION_MINOR is not defined" #endif #ifndef CUCIM_VERSION_PATCH # error "CUCIM_VERSION_PATCH is not defined" #endif #ifndef CUCIM_VERSION_BUILD # error "CUCIM_VERSION_BUILD is not defined" #endif namespace cucim { struct InterfaceVersion { uint32_t major; uint32_t minor; }; struct Version { uint32_t major; uint32_t minor; uint32_t patch; }; } // namespace cucim #endif // CUCIM_VERSION_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/core/plugin.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_PLUGIN_H #define CUCIM_PLUGIN_H #include "cucim/macros/api_header.h" #include "cucim/core/interface.h" #include <cstddef> #include <cstdint> namespace cucim { enum class PluginHotReload : std::uint8_t { kDisabled, kEnabled, }; struct PluginImplDesc { const char* name; Version version; const char* build; const char* author; const char* description; const char* long_description; const char* license; const char* url; const char* platforms; PluginHotReload hot_reload; }; struct PluginEntry { PluginImplDesc desc; struct Interface { InterfaceDesc desc; const void* ptr; size_t size; }; Interface* interfaces; size_t interface_count; }; struct PluginDesc { PluginImplDesc desc; const char* lib_path; const InterfaceDesc* interfaces; size_t interface_count; const InterfaceDesc* dependencies; size_t dependency_count; }; typedef Version(CUCIM_ABI* OnGetFrameworkVersionFn)(); typedef void(CUCIM_ABI* OnPluginRegisterFn)(struct Framework* framework, PluginEntry* out_entry); typedef void(CUCIM_ABI* OnGetPluginDepsFn)(InterfaceDesc** interface_desc, size_t* count); } // namespace cucim #endif // CUCIM_PLUGIN_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/core/plugin_util.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_PLUGIN_UTIL_H #define CUCIM_PLUGIN_UTIL_H #include "plugin.h" constexpr const char* const kCuCIMOnGetFrameworkVersionFnName = "cucim_on_get_framework_version"; // type: OnGetFrameworkVersionFn constexpr const char* const kCuCIMOnPluginRegisterFnName = "cucim_on_plugin_register"; // type: OnPluginRegisterFn /* * Optional functions: */ constexpr const char* const kCuCIMOnGetPluginDepsFnName = "cucim_on_get_plugin_deps"; // type: OnGetPluginDepsFn // const char* const kCarbOnPluginPreStartupFnName = "carbOnPluginPreStartup"; // type: OnPluginPreStartupFn // const char* const kCarbOnPluginStartupFnName = "carbOnPluginStartup"; // type: OnPluginStartupFn // // const char* const kCarbOnPluginShutdownFnName = "carbOnPluginShutdown"; // type: OnPluginShutdownFn // const char* const kCarbOnPluginPostShutdownFnName = "carbOnPluginPostShutdown"; // type: OnPluginPostShutdownFn // // const char* const kCarbOnReloadDependencyFnName = "carbOnReloadDependency"; // type: OnReloadDependencyFn /** * FOR_EACH macro implementation, use as FOR_EACH(OTHER_MACRO, p0, p1, p2,) */ #define EXPAND(x) x #define FE_1(WHAT, X) EXPAND(WHAT(X)) #define FE_2(WHAT, X, ...) EXPAND(WHAT(X) FE_1(WHAT, __VA_ARGS__)) #define FE_3(WHAT, X, ...) EXPAND(WHAT(X) FE_2(WHAT, __VA_ARGS__)) #define FE_4(WHAT, X, ...) EXPAND(WHAT(X) FE_3(WHAT, __VA_ARGS__)) #define FE_5(WHAT, X, ...) EXPAND(WHAT(X) FE_4(WHAT, __VA_ARGS__)) #define FE_6(WHAT, X, ...) EXPAND(WHAT(X) FE_5(WHAT, __VA_ARGS__)) #define FE_7(WHAT, X, ...) EXPAND(WHAT(X) FE_6(WHAT, __VA_ARGS__)) #define FE_8(WHAT, X, ...) EXPAND(WHAT(X) FE_7(WHAT, __VA_ARGS__)) #define FE_9(WHAT, X, ...) EXPAND(WHAT(X) FE_8(WHAT, __VA_ARGS__)) #define FE_10(WHAT, X, ...) EXPAND(WHAT(X) FE_9(WHAT, __VA_ARGS__)) #define FE_11(WHAT, X, ...) EXPAND(WHAT(X) FE_10(WHAT, __VA_ARGS__)) #define FE_12(WHAT, X, ...) EXPAND(WHAT(X) FE_11(WHAT, __VA_ARGS__)) #define FE_13(WHAT, X, ...) EXPAND(WHAT(X) FE_12(WHAT, __VA_ARGS__)) #define FE_14(WHAT, X, ...) EXPAND(WHAT(X) FE_13(WHAT, __VA_ARGS__)) #define FE_15(WHAT, X, ...) EXPAND(WHAT(X) FE_14(WHAT, __VA_ARGS__)) #define FE_16(WHAT, X, ...) EXPAND(WHAT(X) FE_15(WHAT, __VA_ARGS__)) #define FE_17(WHAT, X, ...) EXPAND(WHAT(X) FE_16(WHAT, __VA_ARGS__)) #define FE_18(WHAT, X, ...) EXPAND(WHAT(X) FE_17(WHAT, __VA_ARGS__)) #define FE_19(WHAT, X, ...) EXPAND(WHAT(X) FE_18(WHAT, __VA_ARGS__)) #define FE_20(WHAT, X, ...) EXPAND(WHAT(X) FE_19(WHAT, __VA_ARGS__)) #define FE_21(WHAT, X, ...) EXPAND(WHAT(X) FE_20(WHAT, __VA_ARGS__)) #define FE_22(WHAT, X, ...) EXPAND(WHAT(X) FE_21(WHAT, __VA_ARGS__)) #define FE_23(WHAT, X, ...) EXPAND(WHAT(X) FE_22(WHAT, __VA_ARGS__)) #define FE_24(WHAT, X, ...) EXPAND(WHAT(X) FE_23(WHAT, __VA_ARGS__)) #define FE_25(WHAT, X, ...) EXPAND(WHAT(X) FE_24(WHAT, __VA_ARGS__)) #define FE_26(WHAT, X, ...) EXPAND(WHAT(X) FE_25(WHAT, __VA_ARGS__)) #define FE_27(WHAT, X, ...) EXPAND(WHAT(X) FE_26(WHAT, __VA_ARGS__)) #define FE_28(WHAT, X, ...) EXPAND(WHAT(X) FE_27(WHAT, __VA_ARGS__)) #define FE_29(WHAT, X, ...) EXPAND(WHAT(X) FE_28(WHAT, __VA_ARGS__)) #define FE_30(WHAT, X, ...) EXPAND(WHAT(X) FE_29(WHAT, __VA_ARGS__)) #define FE_31(WHAT, X, ...) EXPAND(WHAT(X) FE_30(WHAT, __VA_ARGS__)) #define FE_32(WHAT, X, ...) EXPAND(WHAT(X) FE_31(WHAT, __VA_ARGS__)) //... repeat as needed #define GET_MACRO(_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, NAME, ...) \ NAME #define FOR_EACH(action, ...) \ EXPAND(GET_MACRO(__VA_ARGS__, FE_32, FE_31, FE_30, FE_29, FE_28, FE_27, FE_26, FE_25, FE_24, FE_23, FE_22, FE_21, \ FE_20, FE_19, FE_18, FE_17, FE_16, FE_15, FE_14, FE_13, FE_12, FE_11, FE_10, FE_9, FE_8, FE_7, \ FE_6, FE_5, FE_4, FE_3, FE_2, FE_1)(action, __VA_ARGS__)) #define DECLARE_FILL_FUNCTION(X) void fill_interface(X& iface); /** * Macros to declare a plugin implementation with custom static initializer. * * It does the following: * * 1. Defines cucim_on_get_framework_version and cucim_on_plugin_register functions. * 2. Defines global framework variable for cucim::getFramework() to work. * 3. Defines global client variable (which is set to a plugin name). It is used for acquiring interfaces, * such that framework knows who calls it. * 4. Forward declares void fill_interface(InterfaceType& iface) functions for every interface to be * used to provide interfaces to the framework. * * This macro must be defined in a global namespace. * * @param impl The PluginImplDesc constant to be used as plugin description. * @param ... One or more interface types to be implemented by the plugin. Interface is a struct with * CUCIM_PLUGIN_INTERFACE() macro inside. */ #define CUCIM_PLUGIN_IMPL_WITH_INIT(impl, ...) \ \ /* Forward declare fill functions for every interface */ \ FOR_EACH(DECLARE_FILL_FUNCTION, __VA_ARGS__) \ \ template <typename T1> \ void fill_interface(cucim::PluginEntry::Interface* interfaces) \ { \ interfaces[0].desc = T1::get_interface_desc(); \ static T1 s_plugin_interface; \ fill_interface(s_plugin_interface); \ interfaces[0].ptr = &s_plugin_interface; \ interfaces[0].size = sizeof(T1); \ } \ \ template <typename T1, typename T2, typename... Types> \ void fill_interface(cucim::PluginEntry::Interface* interfaces) \ { \ fill_interface<T1>(interfaces); \ fill_interface<T2, Types...>(interfaces + 1); \ } \ \ template <typename... Types> \ static void on_plugin_register(cucim::Framework* framework, cucim::PluginEntry* out_entry) \ { \ static cucim::PluginEntry::Interface s_interfaces[sizeof...(Types)]; \ fill_interface<Types...>(s_interfaces); \ out_entry->interfaces = s_interfaces; \ out_entry->interface_count = sizeof(s_interfaces) / sizeof(s_interfaces[0]); \ out_entry->desc = impl; \ \ g_cucim_framework = framework; \ g_cucim_client_name = impl.name; \ } \ \ CUCIM_API void cucim_on_plugin_register(cucim::Framework* framework, cucim::PluginEntry* out_entry) \ { \ on_plugin_register<__VA_ARGS__>(framework, out_entry); \ } \ \ CUCIM_API cucim::Version cucim_on_get_framework_version() \ { \ return cucim::kFrameworkVersion; \ } /** * Macros to declare a plugin implementation dependencies. * * If a plugin lists an interface "A" as dependency it is guaranteed that Framework::acquireInterface<A>() call * will return it, otherwise it can return nullptr. Framework checks and resolves all dependencies before loading the * plugin. * * @param ... One or more interface types to list as dependencies for this plugin. */ #define CUCIM_PLUGIN_IMPL_DEPS(...) \ template <typename... Types> \ static void get_plugin_deps_typed(struct cucim::InterfaceDesc** deps, size_t* count) \ { \ static cucim::InterfaceDesc depends[] = { Types::get_interface_desc()... }; \ *deps = depends; \ *count = sizeof(depends) / sizeof(depends[0]); \ } \ \ CUCIM_API void cucim_on_get_plugin_deps(struct cucim::InterfaceDesc** deps, size_t* count) \ { \ get_plugin_deps_typed<__VA_ARGS__>(deps, count); \ } /** * Macro to declare no plugin implementation dependencies. */ #define CUCIM_PLUGIN_IMPL_NO_DEPS() \ CUCIM_API void cucim_on_get_plugin_deps(struct cucim::InterfaceDesc** deps, size_t* count) \ { \ *deps = nullptr; \ *count = 0; \ } /** * Macro to declare a plugin implementation with an empty scoped initializer. * Useful for those who wants to use bare Carbonite Framework without the pre-registered plugins, * contrary to what CUCIM_PLUGIN_IMPL suggests. */ #define CUCIM_PLUGIN_IMPL_MINIMAL(impl, ...) \ CUCIM_FRAMEWORK_GLOBALS(kPluginImpl.name) \ CUCIM_PLUGIN_IMPL_WITH_INIT(impl, __VA_ARGS__) #endif // CUCIM_PLUGIN_UTIL_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/cpp20/find_if.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #include <algorithm> namespace cucim::cpp20 { // https://en.cppreference.com/w/cpp/algorithm/find #if __cplusplus < 202002L template <class InputIt, class UnaryPredicate> constexpr InputIt find_if(InputIt first, InputIt last, UnaryPredicate p) { for (; first != last; ++first) { if (p(*first)) { return first; } } return last; } #else template <class InputIt, class UnaryPredicate> constexpr InputIt find_if(InputIt first, InputIt last, UnaryPredicate p) { return std::find_if(first, last, p); } #endif }
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/profiler/profiler_config.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_PROFILER_PROFILER_CONFIG_H #define CUCIM_PROFILER_PROFILER_CONFIG_H #include "cucim/core/framework.h" #include <string> #include <vector> namespace cucim::profiler { constexpr bool kDefaultProfilerTrace = false; struct EXPORT_VISIBLE ProfilerConfig { void load_config(const void* json_obj); bool trace = kDefaultProfilerTrace; }; } // namespace cucim::profiler #endif // CUCIM_PROFILER_PROFILER_CONFIG_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/profiler/profiler.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_PROFILER_PROFILER_H #define CUCIM_PROFILER_PROFILER_H #include "cucim/core/framework.h" #include <memory> #include "cucim/profiler/profiler_config.h" namespace cucim::profiler { /** * @brief Profiler class * * Holds the profiler state and provides the interface to configure it. * */ class EXPORT_VISIBLE Profiler : public std::enable_shared_from_this<Profiler> { public: Profiler() = delete; Profiler(ProfilerConfig& config); virtual ~Profiler(){}; ProfilerConfig& config(); ProfilerConfig get_config() const; void trace(bool value); /** * @brief Return whether if trace is enabled or not * * @return true if profiler is enabled. false otherwise */ bool trace() const; protected: ProfilerConfig& config_; }; } // namespace cucim::profiler #endif // CUCIM_PROFILER_PROFILER_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/profiler/nvtx3.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_PROFILER_NVTX3_H #define CUCIM_PROFILER_NVTX3_H #include "cucim/core/framework.h" #if CUCIM_SUPPORT_NVTX # include <cucim/cuimage.h> # include <nvtx3/nvtx3.hpp> // Override nvtx3::v1::scoped_range_in to check whether if "trace" is enabled or not namespace nvtx3::v1 { template <class D = domain::global> class cucim_scoped_range_in { bool enabled_ = false; public: explicit cucim_scoped_range_in(event_attributes const& attr) noexcept { # ifndef NVTX_DISABLE enabled_ = ::cucim::CuImage::is_trace_enabled(); if (enabled_) { nvtxDomainRangePushEx(domain::get<D>(), attr.get()); } # else (void)attr; # endif } template <typename... Args> explicit cucim_scoped_range_in(Args const&... args) noexcept : cucim_scoped_range_in{ event_attributes{ args... } } { } cucim_scoped_range_in() noexcept : cucim_scoped_range_in{ event_attributes{} } { } void* operator new(std::size_t) = delete; cucim_scoped_range_in(cucim_scoped_range_in const&) = delete; cucim_scoped_range_in& operator=(cucim_scoped_range_in const&) = delete; cucim_scoped_range_in(cucim_scoped_range_in&&) = delete; cucim_scoped_range_in& operator=(cucim_scoped_range_in&&) = delete; ~cucim_scoped_range_in() noexcept { # ifndef NVTX_DISABLE if (enabled_) { nvtxDomainRangePop(domain::get<D>()); } # endif } }; } // namespace nvtx3::v1 # define PROF_SCOPED_RANGE(...) \ cucim::profiler::scoped_range _p \ { \ __VA_ARGS__ \ } # define PROF_EVENT(name) \ cucim::profiler::message::get<cucim::profiler::message_##name>(), cucim::profiler::message_##name::category(), \ cucim::profiler::message_##name::color # define PROF_EVENT_P(name, p) \ cucim::profiler::message::get<cucim::profiler::message_##name>(), cucim::profiler::message_##name::category(), \ cucim::profiler::message_##name::color, nvtx3::payload \ { \ p \ } # define PROF_MESSAGE(name) cucim::profiler::message::get<cucim::profiler::message_##name>() # define PROF_CATEGORY(name) cucim::profiler::category::get<cucim::profiler::category_##name>() # define PROF_RGB(r, g, b) \ nvtx3::rgb \ { \ r, g, b \ } # define PROF_ARGB(a, r, g, b) \ nvtx3::argb \ { \ a, r, g, b \ } # define DEFINE_MESSAGE(id, msg) \ struct message_##id \ { \ static constexpr char const* message{ msg }; \ } # define DEFINE_EVENT(id, msg, c, a, r, g, b) \ struct message_##id \ { \ static constexpr char const* message{ msg }; \ static constexpr auto category = []() { \ return cucim::profiler::category::get<cucim::profiler::category_##c>(); \ }; \ static constexpr nvtx3::color color{ nvtx3::argb{ a, r, g, b } }; \ } namespace cucim::profiler { // Domain struct domain { static constexpr char const* name{ "cuCIM" }; }; // Aliases using scoped_range = nvtx3::cucim_scoped_range_in<domain>; using category = nvtx3::named_category<domain>; using message = nvtx3::registered_string<domain>; // Category struct category_io { static constexpr char const* name{ "IO" }; static constexpr uint32_t id{ 10 }; }; struct category_memory { static constexpr char const* name{ "Memory" }; static constexpr uint32_t id{ 20 }; }; struct category_compute { static constexpr char const* name{ "Compute" }; static constexpr uint32_t id{ 30 }; }; // Message/Event DEFINE_EVENT(cucim_malloc, "cucim_malloc()", memory, 255, 63, 72, 204); DEFINE_EVENT(cucim_free, "cucim_free()", memory, 255, 211, 213, 245); DEFINE_EVENT(cucim_plugin_detect_image_format, "ImageFormat::detect_image_format()", io, 255, 255, 0, 0); DEFINE_EVENT(cuimage_cuimage, "CuImage::CuImage()", io, 255, 255, 0, 0); DEFINE_EVENT(cuimage__cuimage, "CuImage::~CuImage()", io, 255, 251, 207, 208); DEFINE_EVENT(cuimage_ensure_init, "CuImage::ensure_init()", io, 255, 255, 0, 0); DEFINE_EVENT(cuimage_ensure_init_plugin_iter, "CuImage::ensure_init::plugin_iter", io, 255, 255, 0, 0); DEFINE_EVENT(cuimage_cuimage_open, "CuImage::CuImage::open", io, 255, 255, 0, 0); DEFINE_EVENT(cuimage_read_region, "CuImage::read_region()", io, 255, 255, 0, 0); DEFINE_EVENT(cuimage_associated_image, "CuImage::associated_image()", io, 255, 255, 0, 0); DEFINE_EVENT(cuimage_crop_image, "CuImage::crop_image()", io, 255, 255, 0, 0); DEFINE_EVENT(image_cache_create_cache, "ImageCacheManager::create_cache()", memory, 255, 63, 72, 204); DEFINE_EVENT(tiff_tiff, "TIFF::TIFF()", io, 255, 255, 0, 0); DEFINE_EVENT(tiff__tiff, "TIFF::~TIFF()", io, 255, 251, 207, 208); DEFINE_EVENT(tiff_construct_ifds, "TIFF::construct_ifds()", io, 255, 255, 0, 0); DEFINE_EVENT(tiff_resolve_vendor_format, "TIFF::resolve_vendor_format()", io, 255, 255, 0, 0); DEFINE_EVENT(tiff_read, "TIFF::read()", io, 255, 255, 0, 0); DEFINE_EVENT(tiff_read_associated_image, "TIFF::read_associated_image()", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_ifd, "IFD::IFD()", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_read, "IFD::read()", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_read_slowpath, "IFD::read::slow_path", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_read_region_tiles, "IFD::read_region_tiles()", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_read_region_tiles_iter, "IFD::read_region_tiles::iter", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_read_region_tiles_task, "IFD::read_region_tiles::task", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_read_region_tiles_boundary, "IFD::read_region_tiles_boundary()", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_read_region_tiles_boundary_iter, "IFD::read_region_tiles_boundary::iter", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_read_region_tiles_boundary_task, "IFD::read_region_tiles_boundary::task", io, 255, 255, 0, 0); DEFINE_EVENT(ifd_decompression, "IFD::decompression", compute, 255, 0, 255, 0); DEFINE_EVENT(decoder_libjpeg_turbo_tjAlloc, "libjpeg-turbo::tjAlloc()", memory, 255, 63, 72, 204); DEFINE_EVENT(decoder_libjpeg_turbo_tjFree, "libjpeg-turbo::tjFree()", memory, 255, 211, 213, 245); DEFINE_EVENT(decoder_libjpeg_turbo_tjInitDecompress, "libjpeg-turbo::tjInitDecompress()", compute, 255, 0, 255, 0); DEFINE_EVENT(decoder_libjpeg_turbo_tjDecompressHeader3, "libjpeg-turbo::tjDecompressHeader3()", compute, 255, 0, 255, 0); DEFINE_EVENT(decoder_libjpeg_turbo_tjDestroy, "libjpeg-turbo::tjDestroy()", compute, 255, 0, 255, 0); DEFINE_EVENT( decoder_libjpeg_turbo_read_jpeg_header_tables, "cuslide::jpeg::read_jpeg_header_tables()", compute, 255, 0, 255, 0); DEFINE_EVENT(decoder_libjpeg_turbo_jpeg_decode_buffer, "cuslide::jpeg::jpeg_decode_buffer()", compute, 255, 0, 255, 0); DEFINE_EVENT(libdeflate_alloc_decompressor, "libdeflate::libdeflate_alloc_decompressor()", memory, 255, 63, 72, 204); DEFINE_EVENT(libdeflate_zlib_decompress, "libdeflate::libdeflate_zlib_decompress()", compute, 255, 0, 255, 0); DEFINE_EVENT(libdeflate_free_decompressor, "libdeflate::libdeflate_free_decompressor()", memory, 255, 211, 213, 245); DEFINE_EVENT(opj_stream_create, "libopenjpeg::opj_stream_create()", compute, 255, 0, 255, 0); DEFINE_EVENT(opj_create_decompress, "libopenjpeg::opj_create_decompress()", compute, 255, 0, 255, 0); DEFINE_EVENT(opj_read_header, "libopenjpeg::opj_read_header()", compute, 255, 0, 255, 0); DEFINE_EVENT(opj_decode, "libopenjpeg::opj_decode()", compute, 255, 0, 255, 0); DEFINE_EVENT(color_sycc_to_rgb, "libopenjpeg::color_sycc_to_rgb()", compute, 255, 0, 255, 0); DEFINE_EVENT(color_apply_icc_profile, "libopenjpeg::color_apply_icc_profile()", compute, 255, 0, 255, 0); DEFINE_EVENT(opj_destructions, "libopenjpeg::opj_destructions", compute, 255, 0, 255, 0); DEFINE_EVENT(jpeg2k_fast_sycc422_to_rgb, "jpeg2k::fast_sycc422_to_rgb()", compute, 255, 0, 255, 0); DEFINE_EVENT(jpeg2k_fast_sycc420_to_rgb, "jpeg2k::fast_sycc420_to_rgb()", compute, 255, 0, 255, 0); DEFINE_EVENT(jpeg2k_fast_sycc444_to_rgb, "jpeg2k::fast_sycc444_to_rgb()", compute, 255, 0, 255, 0); DEFINE_EVENT(jpeg2k_fast_image_to_rgb, "jpeg2k::fast_image_to_rgb()", compute, 255, 0, 255, 0); DEFINE_EVENT(lzw_TIFFInitLZW, "lzw::TIFFInitLZW()", compute, 255, 0, 255, 0); DEFINE_EVENT(lzw_LZWSetupDecode, "lzw::LZWSetupDecode()", compute, 255, 0, 255, 0); DEFINE_EVENT(lzw_LZWPreDecode, "lzw::LZWPreDecode()", compute, 255, 0, 255, 0); DEFINE_EVENT(lzw_LZWDecode, "lzw::LZWDecode()", compute, 255, 0, 255, 0); DEFINE_EVENT(lzw_LZWCleanup, "lzw::LZWCleanup()", compute, 255, 0, 255, 0); DEFINE_EVENT(lzw_horAcc8, "lzw::LZWCleanup()", compute, 255, 0, 255, 0); } // namespace cucim::profiler #else # define PROF_SCOPED_RANGE(...) ((void)0) # define PROF_EVENT(name) ((void)0) # define PROF_EVENT_P(name, p) ((void)0) # define PROF_MESSAGE(name) ((void)0) # define PROF_CATEGORY(name) ((void)0) # define PROF_RGB(r, g, b) ((void)0) # define PROF_ARGB(a, r, g, b) ((void)0) # define DEFINE_MESSAGE(id, msg) ((void)0) # define DEFINE_EVENT(id, msg, c, p, a, r, g, b) ((void)0) #endif // CUCIM_SUPPORT_NVTX #endif // CUCIM_PROFILER_NVTX3_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/filesystem/cufile_driver.h
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_CUFILE_DRIVER_H #define CUCIM_CUFILE_DRIVER_H #include "file_handle.h" #include "file_path.h" #include <memory> #include <mutex> namespace cucim::filesystem { using Mutex = std::mutex; using ScopedLock = std::scoped_lock<Mutex>; // Forward declaration. class CuFileDriver; /** * @brief Check if the GDS is available in the system. * * @return true if libcufile.so is loaded and cuFileDriverOpen() API call succeeds. */ bool EXPORT_VISIBLE is_gds_available(); /** * Open file with specific flags and mode. * * 'flags' can be one of the following flag string: * - "r": O_RDONLY * - "r+": O_RDWR * - "w": O_RDWR | O_CREAT | O_TRUNC * - "a": O_RDWR | O_CREAT * In addition to above flags, the method append O_CLOEXEC and O_DIRECT by default. * * The following is optional flags that can be added to above string: * - 'p': Use POSIX APIs only (first try to open with O_DIRECT). It does not use GDS. * - 'n': Do not add O_DIRECT flag. * - 'm': Use memory-mapped file. This flag is supported only for the read-only file descriptor. * * When 'm' is used, `PROT_READ` and `MAP_SHARED` are used for the parameter of mmap() function. * * @param file_path A file path to open. * @param flags File flags in string. Default value is "r". * @param mode A file mode. Default value is '0644'. * @return a std::shared_ptr object of CuFileDriver. */ std::shared_ptr<CuFileDriver> EXPORT_VISIBLE open(const char* file_path, const char* flags = "r", mode_t mode = 0644); /** * Open file with existing file descriptor. * * @param fd A file descriptor. To use GDS, fd needs to be opened with O_DIRECT flag. * @param no_gds true if you do not want to use GDS. Default value is `false`. * @param use_mmap true if you want to use memory-mapped IO. This flag is supported only for the read-only file descriptor. Default value is `false`. * @return A std::shared_ptr object of CuFileDriver. */ std::shared_ptr<CuFileDriver> EXPORT_VISIBLE open(int fd, bool no_gds = false, bool use_mmap = false); /** * Close the given file driver. * * @param fd A std::shared_ptr object of CuFileDriver. * @return true if succeed, false otherwise. */ bool EXPORT_VISIBLE close(const std::shared_ptr<CuFileDriver>& fd); /** * Read up to `count` bytes from file driver `fd` at offset `file_offset` (from the start of the file) into the buffer * `buf` at offset `buf_offset`. The file offset is not changed. * * @param fd A std::shared_ptr object of CuFileDriver. * @param buf A buffer where read bytes are stored. Buffer can be either in CPU memory or (CUDA) GPU memory. * @param count The number of bytes to read. * @param file_offset An offset from the start of the file. * @param buf_offset An offset from the start of the buffer. Default value is 0. * @return The number of bytes read if succeed, -1 otherwise. */ ssize_t EXPORT_VISIBLE pread(const std::shared_ptr<CuFileDriver>& fd, void* buf, size_t count, off_t file_offset, off_t buf_offset = 0); /** * Write up to `count` bytes from the buffer `buf` at offset `buf_offset` to the file driver `fd` at offset * `file_offset` (from the start of the file). The file offset is not changed. * * * @param fd A std::shared_ptr object of CuFileDriver. * @param buf A buffer where write bytes come from. Buffer can be either in CPU memory or (CUDA) GPU memory. * @param count The number of bytes to write. * @param file_offset An offset from the start of the file. * @param buf_offset An offset from the start of the buffer. Default value is 0. * @return The number of bytes written if succeed, -1 otherwise. */ ssize_t EXPORT_VISIBLE pwrite(const std::shared_ptr<CuFileDriver>& fd, const void* buf, size_t count, off_t file_offset, off_t buf_offset = 0); /** * Discard a system (page) cache for the given file path. * @param file_path A file path to drop system cache. * @return true if succeed, false otherwise. */ bool EXPORT_VISIBLE discard_page_cache(const char* file_path); class CuFileDriverInitializer { public: CuFileDriverInitializer(); inline operator bool() const { return is_available_; } inline uint64_t max_device_cache_size() const { return max_device_cache_size_; } inline uint64_t max_host_cache_size() const { return max_host_cache_size_; } ~CuFileDriverInitializer(); private: bool is_available_ = false; uint64_t max_device_cache_size_ = 0; uint64_t max_host_cache_size_ = 0; }; class CuFileDriverCache { public: CuFileDriverCache(); void* device_cache(); void* host_cache(); inline bool is_device_cache_available() { return !!device_cache_; } inline bool is_host_cache_available() { return !!host_cache_; } ~CuFileDriverCache(); private: void* device_cache_ = nullptr; void* device_cache_aligned_ = nullptr; void* host_cache_ = nullptr; void* host_cache_aligned_ = nullptr; }; class EXPORT_VISIBLE CuFileDriver : public std::enable_shared_from_this<CuFileDriver> { public: CuFileDriver() = delete; CuFileDriver(int fd, bool no_gds = false, bool use_mmap = false, const char* file_path = nullptr); ssize_t pread(void* buf, size_t count, off_t file_offset, off_t buf_offset = 0) const; ssize_t pwrite(const void* buf, size_t count, off_t file_offset, off_t buf_offset = 0); bool close(); filesystem::Path path() const; ~CuFileDriver(); // To allow 'handle_' field friend std::shared_ptr<CuFileDriver> open(const char* file_path, const char* flags, mode_t mode); private: static Mutex driver_mutex_; // TODO: not used yet. std::string file_path_; size_t file_size_ = 0; int file_flags_ = -1; void* mmap_ptr_ = nullptr; std::shared_ptr<CuCIMFileHandle> handle_; }; } // namespace cucim::filesystem #endif // CUCIM_CUFILE_DRIVER_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/filesystem/file_path.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_FILE_PATH_H #define CUCIM_FILE_PATH_H #include <string> namespace cucim::filesystem { using Path = std::string; } // namespace cucim::filesystem #endif // CUCIM_FILE_PATH_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/filesystem/file_handle.h
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_FILE_HANDLE_H #define CUCIM_FILE_HANDLE_H #include "../macros/defines.h" #include <unistd.h> #include <cstdio> #include <cstdint> #include <memory> #include <fmt/format.h> #include "cucim/memory/memory_manager.h" typedef void* CUfileHandle_t; typedef void* CuCIMFileHandle_share; typedef void* CuCIMFileHandle_ptr; typedef bool (*CuCIMFileHandleDeleter)(CuCIMFileHandle_ptr); enum class FileHandleType : uint16_t { kUnknown = 0, kPosix = 1, kPosixODirect = 1 << 1, kMemoryMapped = 1 << 2, kGPUDirect = 1 << 3, }; #if CUCIM_PLATFORM_LINUX struct EXPORT_VISIBLE CuCIMFileHandle : public std::enable_shared_from_this<CuCIMFileHandle> { CuCIMFileHandle(); CuCIMFileHandle(int fd, CUfileHandle_t cufile, FileHandleType type, char* path, void* client_data); CuCIMFileHandle(int fd, CUfileHandle_t cufile, FileHandleType type, char* path, void* client_data, uint64_t dev, uint64_t ino, int64_t mtime, bool own_fd); ~CuCIMFileHandle() { if (path && path[0] != '\0') { cucim_free(path); path = nullptr; } if (deleter) { deleter(this); deleter = nullptr; } if (own_fd && fd >=0) { ::close(fd); fd = -1; own_fd = false; } } CuCIMFileHandleDeleter set_deleter(CuCIMFileHandleDeleter deleter) { return this->deleter = deleter; } int fd = -1; CUfileHandle_t cufile = nullptr; FileHandleType type = FileHandleType::kUnknown; /// 1: POSIX, 2: POSIX+ODIRECT, 4: MemoryMapped, 8: GPUDirect char* path = nullptr; void* client_data = nullptr; uint64_t hash_value = 0; uint64_t dev = 0; uint64_t ino = 0; int64_t mtime = 0; bool own_fd = false; /// whether if the file descriptor is created internally by the driver CuCIMFileHandleDeleter deleter = nullptr; }; #else # error "This platform is not supported!" #endif #endif // CUCIM_FILE_HANDLE_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/concurrent/threadpool.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_CONCURRENT_THREADPOOL_H #define CUCIM_CONCURRENT_THREADPOOL_H #include "cucim/macros/api_header.h" #include <functional> #include <future> #include <memory> namespace cucim::concurrent { class EXPORT_VISIBLE ThreadPool { public: explicit ThreadPool(int32_t num_workers); ThreadPool(const ThreadPool&) = delete; ThreadPool& operator=(const ThreadPool&) = delete; operator bool() const; ~ThreadPool(); std::future<void> enqueue(std::function<void()> task); void wait(); private: struct Executor; std::unique_ptr<Executor> executor_; size_t num_workers_; }; } // namespace cucim::concurrent #endif // CUCIM_CONCURRENT_THREADPOOL_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/memory/dlpack.h
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_DLPACK_H #define CUCIM_DLPACK_H #include "dlpack/dlpack.h" #include <fmt/format.h> namespace cucim::memory { /** * @brief Return a string providing the basic type of the homogeneous array in NumPy. * * Note: This method assumes little-endian for now. * * @return A const character pointer that represents a string from a given `DLDataType` data. */ inline const char* to_numpy_dtype(const DLDataType& dtype) { // TODO: consider bfloat16: https://github.com/dmlc/dlpack/issues/45 // TODO: consider other byte-order uint8_t code = dtype.code; uint8_t bits = dtype.bits; switch(code) { case kDLInt: switch(bits) { case 8: return "|i1"; case 16: return "<i2"; case 32: return "<i4"; case 64: return "<i8"; } throw std::logic_error(fmt::format("DLDataType(code: kDLInt, bits: {}) is not supported!", bits)); case kDLUInt: switch(bits) { case 8: return "|u1"; case 16: return "<u2"; case 32: return "<u4"; case 64: return "<u8"; } throw std::logic_error(fmt::format("DLDataType(code: kDLUInt, bits: {}) is not supported!", bits)); case kDLFloat: switch(bits) { case 16: return "<f2"; case 32: return "<f4"; case 64: return "<f8"; } break; case kDLBfloat: throw std::logic_error(fmt::format("DLDataType(code: kDLBfloat, bits: {}) is not supported!", bits)); } throw std::logic_error(fmt::format("DLDataType(code: {}, bits: {}) is not supported!", code, bits)); } class DLTContainer { public: DLTContainer() = delete; DLTContainer(DLTensor* handle, char* shm_name = nullptr) : tensor_(handle), shm_name_(shm_name) { } /** * @brief Return the size of memory required to store the contents of data. * * @return size_t Required size for the tensor. */ size_t size() const { size_t size = 1; for (int i = 0; i < tensor_->ndim; ++i) { size *= tensor_->shape[i]; } size *= (tensor_->dtype.bits * tensor_->dtype.lanes + 7) / 8; return size; } DLDataType dtype() const { if (!tensor_) { return DLDataType({ DLDataTypeCode::kDLUInt, 8, 1 }); } return tensor_->dtype; } /** * @brief Return a string providing the basic type of the homogeneous array in NumPy. * * Note: This method assumes little-endian for now. * * @return A const character pointer that represents a string */ const char* numpy_dtype() const { // TODO: consider bfloat16: https://github.com/dmlc/dlpack/issues/45 // TODO: consider other byte-order if (!tensor_) { return ""; } return to_numpy_dtype(tensor_->dtype); } operator bool() const { return static_cast<bool>(tensor_); } operator DLTensor() const { if (tensor_) { return *tensor_; } else { return DLTensor{}; } } operator DLTensor*() const { return tensor_; } private: DLTensor* tensor_ = nullptr; char* shm_name_ = nullptr; }; } // namespace cucim::memory #endif // CUCIM_DLPACK_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/memory/memory_manager.h
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * 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. */ // #ifndef CUCIM_MEMORY_MANAGER_H #define CUCIM_MEMORY_MANAGER_H #include "cucim/macros/api_header.h" #include <cstddef> #include "cucim/io/device.h" /** * Host memory allocator for exchanged data * @param size Number of bytes to allocate * @return Pointer to the allocated memory */ CUCIM_API void* cucim_malloc(size_t size); /** * Free allocated memory by cucim_malloc * @param Pointer to the allocated memory */ CUCIM_API void cucim_free(void* ptr); namespace cucim::memory { /** * Pointer attributes */ struct PointerAttributes { /** * @brief The type of device */ cucim::io::Device device{}; /** * The address which may be dereferenced on the current device to access * the memory or nullptr if no such address exists. */ void* ptr = nullptr; }; /** * @brief A wrapper for cudaPointerGetAttributes() in CUDA. * * Instead of cudaPointerAttributes * * @param ptr Pointer to the allocated memory * @return Pointer attribute information in 'PointerAttributes' struct */ CUCIM_API void get_pointer_attributes(PointerAttributes& attr, const void* ptr); /** * @brief Move host memory of `size` bytes to a new memory in `out_device`. * * Set the pointer of the new memory to `target` and free the host memory previously indicated by `target. * Do nothing if `out_device` is CPU memory. * * @param[in, out] target Pointer to the pointer of the host memory. * @param size Size of the host memory. * @param dst_device Destination device of the memory. * @return `true` if succeed. */ CUCIM_API bool move_raster_from_host(void** target, size_t size, const cucim::io::Device& dst_device); /** * @brief Move device memory of `size` bytes to a new memory in `out_device`. * * Set the pointer of the new memory to `target` and free the device memory previously indicated by `target. * Do nothing if `out_device` is CUDA memory. * * @param[in, out] target Pointer to the pointer of the device memory. * @param size Size of the device memory. * @param dst_device Destination device of the memory. * @return `true` if succeed. */ CUCIM_API bool move_raster_from_device(void** target, size_t size, const cucim::io::Device& dst_device); } // namespace cucim::memory #endif // CUCIM_MEMORY_MANAGER_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/loader/tile_info.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_LOADER_TILE_INFO_H #define CUCIM_LOADER_TILE_INFO_H #include "cucim/macros/api_header.h" #include <cstdint> namespace cucim::loader { struct EXPORT_VISIBLE TileInfo { int64_t location_index = 0; // patch # int64_t index = 0; // tile # uint64_t offset = 0; uint64_t size = 0; }; } // namespace cucim::loader #endif // CUCIM_LOADER_TILE_INFO_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/loader/batch_data_processor.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_LOADER_BATCH_DATA_PROCESSOR_H #define CUCIM_LOADER_BATCH_DATA_PROCESSOR_H #include "cucim/macros/api_header.h" #include <cstdint> #include <deque> #include <cucim/cache/image_cache.h> #include "tile_info.h" namespace cucim::loader { class EXPORT_VISIBLE BatchDataProcessor { public: BatchDataProcessor(uint32_t batch_size); virtual ~BatchDataProcessor(); void add_tile(const TileInfo& tile); TileInfo remove_front_tile(); virtual uint32_t request(std::deque<uint32_t>& batch_item_counts, const uint32_t num_remaining_patches); virtual uint32_t wait_batch(const uint32_t index_in_task, std::deque<uint32_t>& batch_item_counts, const uint32_t num_remaining_patches); virtual std::shared_ptr<cucim::cache::ImageCacheValue> wait_for_processing(uint32_t); virtual void shutdown(); protected: uint32_t batch_size_ = 1; uint64_t total_index_count_ = 0; uint64_t processed_index_count_ = 0; std::deque<TileInfo> tiles_; }; } // namespace cucim::loader #endif // CUCIM_LOADER_BATCH_DATA_PROCESSOR_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/loader/thread_batch_data_loader.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_LOADER_THREAD_BATCH_DATA_LOADER_H #define CUCIM_LOADER_THREAD_BATCH_DATA_LOADER_H #include "cucim/macros/api_header.h" #include <cstdint> #include <deque> #include <memory> #include <vector> #include "cucim/cache/image_cache.h" #include "cucim/concurrent/threadpool.h" #include "cucim/io/device.h" #include "cucim/loader/batch_data_processor.h" #include "cucim/loader/tile_info.h" namespace cucim::loader { class EXPORT_VISIBLE ThreadBatchDataLoader { public: using LoadFunc = std::function<void(ThreadBatchDataLoader* loader_ptr, uint64_t location_index)>; ThreadBatchDataLoader(LoadFunc load_func, std::unique_ptr<BatchDataProcessor> batch_data_processor, cucim::io::Device out_device, std::unique_ptr<std::vector<int64_t>> location, std::unique_ptr<std::vector<int64_t>> image_size, uint64_t location_len, size_t one_raster_size, uint32_t batch_size, uint32_t prefetch_factor, uint32_t num_workers); ~ThreadBatchDataLoader(); operator bool() const; uint8_t* raster_pointer(uint64_t location_index) const; uint32_t request(uint32_t load_size = 0); uint32_t wait_batch(); /** * @brief Return the next batch of data. * * If the number of workers is zero, this function will return the ownership of the data. * @return uint8_t* The pointer to the data. */ uint8_t* next_data(); BatchDataProcessor* batch_data_processor(); std::shared_ptr<cucim::cache::ImageCacheValue> wait_for_processing(uint32_t index); uint64_t size() const; uint32_t batch_size() const; uint64_t total_batch_count() const; uint64_t processed_batch_count() const; uint8_t* data() const; uint32_t data_batch_size() const; bool enqueue(std::function<void()> task, const TileInfo& tile); private: bool stopped_ = false; LoadFunc load_func_; cucim::io::Device out_device_; std::unique_ptr<std::vector<int64_t>> location_ = nullptr; std::unique_ptr<std::vector<int64_t>> image_size_ = nullptr; uint64_t location_len_ = 0; size_t one_rester_size_ = 0; uint32_t batch_size_ = 1; uint32_t prefetch_factor_ = 2; uint32_t num_workers_ = 0; // For nvjpeg std::unique_ptr<BatchDataProcessor> batch_data_processor_; size_t buffer_item_len_ = 0; size_t buffer_size_ = 0; std::vector<uint8_t*> raster_data_; std::deque<std::future<void>> tasks_; // NOTE: the order is important ('thread_pool_' depends on 'raster_data_' and 'tasks_') cucim::concurrent::ThreadPool thread_pool_; uint64_t queued_item_count_ = 0; uint64_t buffer_item_head_index_ = 0; uint64_t buffer_item_tail_index_ = 0; std::deque<uint32_t> batch_item_counts_; uint64_t processed_batch_count_ = 0; uint8_t* current_data_ = nullptr; uint32_t current_data_batch_size_ = 0; }; } // namespace cucim::loader #endif // CUCIM_LOADER_THREAD_BATCH_DATA_LOADER_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/plugin/plugin_config.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_PLUGIN_PLUGIN_CONFIG_H #define CUCIM_PLUGIN_PLUGIN_CONFIG_H #include "cucim/core/framework.h" #include <string> #include <vector> namespace cucim::plugin { #define XSTR(x) STR(x) #define STR(x) #x struct EXPORT_VISIBLE PluginConfig { void load_config(const void* json_obj); std::vector<std::string> plugin_names{ std::string("cucim.kit.cuslide@" XSTR(CUCIM_VERSION) ".so"), std::string("cucim.kit.cumed@" XSTR(CUCIM_VERSION) ".so") }; }; #undef STR #undef XSTR } // namespace cucim::plugin #endif // CUCIM_PLUGIN_PLUGIN_CONFIG_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/plugin/image_format.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_PLUGIN_IMAGE_FORMAT_H #define CUCIM_PLUGIN_IMAGE_FORMAT_H #include "cucim/filesystem/file_path.h" #include "cucim/io/format/image_format.h" namespace cucim::plugin { class ImageFormat { public: ImageFormat() = default; ~ImageFormat() = default; bool add_interfaces(const cucim::io::format::IImageFormat* image_formats); cucim::io::format::ImageFormatDesc* detect_image_format(const filesystem::Path& path); operator bool() const { return !image_formats_.empty(); } private: std::vector<cucim::io::format::ImageFormatDesc*> image_formats_; }; } // namespace cucim::plugin #endif // CUCIM_PLUGIN_IMAGE_FORMAT_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/macros/defines.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_DEFINES_H #define CUCIM_DEFINES_H #include "cucim/macros/api_header.h" /******************************************************************************* Platform-related definitions *******************************************************************************/ /******************************************************************************* Memory-related definitions *******************************************************************************/ #define CUCIM_ALIGN_AS(T) alignas(T) /******************************************************************************* Debug-related definitions *******************************************************************************/ #if CUCIM_PLATFORM_LINUX # include <signal.h> # define CUCIM_BREAK_POINT() ::raise(SIGTRAP) #elif CUCIM_PLATFORM_WINDOWS # define CUCIM_BREAK_POINT() ::__debugbreak() #else # error "This platform is not supported!" #endif #define CUCIM_CHECK_ENABLED 1 #define CUCIM_CHECK(cond, ...) ((void)0) #if CUCIM_DEBUG # define CUCIM_ASSERT_ENABLED 1 # define CUCIM_ASSERT(cond, ...) CUCIM_CHECK(cond, ##__VA_ARGS__) #else # define CUCIM_ASSERT_ENABLED 0 # define CUCIM_ASSERT(cond, ...) (void)0; #endif #include <cstdio> #include <cinttypes> #define CUCIM_LOG_VERBOSE(fmt, ...) ::fprintf(stderr, fmt "\n", ##__VA_ARGS__) #define CUCIM_LOG_INFO(fmt, ...) ::fprintf(stderr, fmt "\n", ##__VA_ARGS__) #define CUCIM_LOG_WARN(fmt, ...) ::fprintf(stderr, fmt "\n", ##__VA_ARGS__) #define CUCIM_LOG_ERROR(fmt, ...) ::fprintf(stderr, fmt "\n", ##__VA_ARGS__) #define CUCIM_LOG_FATAL(fmt, ...) ::fprintf(stderr, fmt "\n", ##__VA_ARGS__) #include <exception> #define CUCIM_ERROR(fmt, ...) \ do \ { \ ::fprintf(stderr, fmt "\n", ##__VA_ARGS__); \ throw std::runtime_error("Error!"); \ } while (0) // Check float type size #include <climits> static_assert(sizeof(float) * CHAR_BIT == 32, "float data type is not 32 bits!"); #endif // CUCIM_DEFINES_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/macros/api_header.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_API_H #define CUCIM_API_H #if defined(__linux__) # define CUCIM_PLATFORM_LINUX 1 # define CUCIM_PLATFORM_WINDOWS 0 #elif _WIN32 # define CUCIM_PLATFORM_LINUX 0 # define CUCIM_PLATFORM_WINDOWS 1 #else # error "This platform is not supported!" #endif #if CUCIM_PLATFORM_WINDOWS # define CUCIM_ABI __cdecl #else # define CUCIM_ABI #endif //#ifdef CARB_EXPORTS //# ifdef __cplusplus //# define CARB_EXPORT_C extern "C" //# else //# define CARB_EXPORT_C //# endif // //# undef CARB_EXPORT //# define CARB_EXPORT CARB_EXPORT_C CARB_DECLSPEC(dllexport) CARB_ATTRIBUTE(visibility("default")) //#else //# undef CARB_EXPORT //# define CARB_EXPORT extern "C" //#endif #ifndef EXPORT_VISIBLE # define EXPORT_VISIBLE __attribute__((visibility("default"))) #endif #ifndef EXPORT_HIDDEN # define EXPORT_HIDDEN __attribute__((visibility("hidden"))) #endif #ifdef CUCIM_STATIC_DEFINE # define CUCIM_API # define CUCIM_NO_EXPORT #else # ifdef __cplusplus # define CUCIM_EXPORT_C extern "C" # else # define CUCIM_EXPORT_C # endif # ifdef CUCIM_EXPORTS # undef CUCIM_API # define CUCIM_API CUCIM_EXPORT_C EXPORT_VISIBLE # else # undef CUCIM_API # define CUCIM_API CUCIM_EXPORT_C # endif # ifndef CUCIM_NO_EXPORT # define CUCIM_NO_EXPORT EXPORT_HIDDEN # endif #endif #ifndef CUCIM_DEPRECATED # define CUCIM_DEPRECATED __attribute__((__deprecated__)) #endif #ifndef CUCIM_DEPRECATED_EXPORT # define CUCIM_DEPRECATED_EXPORT CUCIM_API CUCIM_DEPRECATED #endif #ifndef CUCIM_DEPRECATED_NO_EXPORT # define CUCIM_DEPRECATED_NO_EXPORT CUCIM_NO_EXPORT CUCIM_DEPRECATED #endif #if 0 /* DEFINE_NO_DEPRECATED */ # ifndef CUCIM_NO_DEPRECATED # define CUCIM_NO_DEPRECATED # endif #endif #endif /* CUCIM_API_H */
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/codec/base64.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_BASE64_H #define CUCIM_BASE64_H #include "cucim/macros/defines.h" namespace cucim::codec::base64 { EXPORT_VISIBLE bool encode(const char* src, int src_count, char** out_dst, int* out_count); EXPORT_VISIBLE bool decode(const char* src, int src_count, char** out_dst, int* out_count); } #endif // CUCIM_BASE64_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/codec/hash_function.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_HASH_FUNCTION_H #define CUCIM_HASH_FUNCTION_H #include <cstdint> namespace cucim::codec { /** * @brief splitmix64 hash function with three input values * * This function based on the code from https://xorshift.di.unimi.it/splitmix64.c which is released in the public * domain (http://creativecommons.org/publicdomain/zero/1.0/). * * @param x input state value * @return uint64_t */ inline uint64_t splitmix64(uint64_t x) { uint64_t z = (x += 0x9e3779b97f4a7c15); z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >> 27)) * 0x94d049bb133111eb; return z ^ (z >> 31); } /** * @brief splitmix64 hash function with three input values * * This function based on the code from https://xorshift.di.unimi.it/splitmix64.c which is released in the public * domain (http://creativecommons.org/publicdomain/zero/1.0/). * * @param a * @param b * @param c * @return uint64_t */ inline uint64_t splitmix64_3(uint64_t a, uint64_t b, uint64_t c) { uint64_t z = (a += 0x9e3779b97f4a7c15); z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >> 27)) * 0x94d049bb133111eb; z = z ^ (z >> 31); z += (b += 0x9e3779b97f4a7c15); z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >> 27)) * 0x94d049bb133111eb; z = z ^ (z >> 31); z += (c += 0x9e3779b97f4a7c15); z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >> 27)) * 0x94d049bb133111eb; z = z ^ (z >> 31); return z; } } // namespace cucim::codec #endif // CUCIM_HASH_FUNCTION_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/codec/methods.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_METHODS_H #define CUCIM_METHODS_H #include "cucim/macros/defines.h" namespace cucim::codec { /// Compression method (Followed https://www.awaresystems.be/imaging/tiff/tifftags/compression.html) enum class CompressionMethod : uint16_t { NONE = 1, JPEG = 7, }; } // namespace cucim::codec #endif // CUCIM_METHODS_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/io/device_type.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_IO_DEVICE_TYPE_H #define CUCIM_IO_DEVICE_TYPE_H #include "cucim/macros/api_header.h" #include <array> #include <cstdint> #include <string_view> namespace cucim::io { using DeviceIndex = int16_t; constexpr std::size_t kDeviceTypeCount = 6; /** * Value for each device type follows https://github.com/dmlc/dlpack/blob/v0.6/include/dlpack/dlpack.h * Naming convention follows PyTorch (torch/include/c10/core/DeviceType.h) */ enum class DeviceType : int16_t { kCPU = 1, kCUDA = 2, kCUDAHost = 3, kCUDAManaged = 13, kCPUShared = 101, /// custom type for CPU-shared memory kCUDAShared = 102, /// custom type for GPU-shared memory }; // Using constexpr map (https://www.youtube.com/watch?v=INn3xa4pMfg) struct DeviceTypeMap { std::array<std::pair<std::string_view, DeviceType>, kDeviceTypeCount> data; [[nodiscard]] constexpr DeviceType at(const std::string_view& key) const; }; EXPORT_VISIBLE DeviceType lookup_device_type(const std::string_view sv); struct DeviceTypeStrMap { std::array<std::pair<DeviceType, std::string_view>, kDeviceTypeCount> data; [[nodiscard]] constexpr std::string_view at(const DeviceType& key) const; }; EXPORT_VISIBLE std::string_view lookup_device_type_str(const DeviceType type); } // namespace cucim::io #endif // CUCIM_IO_DEVICE_TYPE_H
0
rapidsai_public_repos/cucim/cpp/include/cucim
rapidsai_public_repos/cucim/cpp/include/cucim/io/device.h
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_IO_DEVICE_H #define CUCIM_IO_DEVICE_H #include "cucim/macros/api_header.h" #include <cstdint> #include <string> #include "device_type.h" namespace cucim::io { using DeviceIndex = int16_t; // Make the following public libraries visible (default visibility) as this header's implementation is in device.cpp // and provided by cucim library. // Without that, a plugin module cannot find the definition of those methods when Device class is used in the plugin // module. class EXPORT_VISIBLE Device { public: explicit Device(); Device(const Device& device); Device& operator=(const Device& device) = default; explicit Device(const std::string& device_name); Device(const char* device_name); Device(DeviceType type, DeviceIndex index); Device(DeviceType type, DeviceIndex index, const std::string& param); static DeviceType parse_type(const std::string& device_name); explicit operator std::string() const; DeviceType type() const; DeviceIndex index() const; const std::string& shm_name() const; void set_values(DeviceType type, DeviceIndex index = -1, const std::string& param = ""); private: DeviceType type_ = DeviceType::kCPU; DeviceIndex index_ = -1; std::string shm_name_; /// used for shared memory name bool validate_device(); }; } // namespace cucim::io #endif // CUCIM_IO_DEVICE_H
0
rapidsai_public_repos/cucim/cpp/include/cucim/io
rapidsai_public_repos/cucim/cpp/include/cucim/io/format/image_format.h
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * 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. */ #ifndef CUCIM_IMAGE_FORMAT_H #define CUCIM_IMAGE_FORMAT_H #include "cucim/core/interface.h" #include "cucim/filesystem/file_handle.h" #include "dlpack/dlpack.h" #include <memory_resource> #include <string> namespace cucim::io::format { struct DimIndicesDesc { int64_t indices[26]; /// Indices for each alphabet ('A'= 0, 'Z'= 25) }; struct ResolutionInfoDesc { uint16_t level_count; uint16_t level_ndim; int64_t* level_dimensions; float* level_downsamples; uint32_t* level_tile_sizes; }; struct AssociatedImageInfoDesc { uint16_t image_count; char** image_names; }; struct ImageMetadataDesc { void* handle; /// Handle for ImageMetadata object uint16_t ndim; /// Number of dimensions const char* dims; /// Dimension characters (E.g., "STCZYX") int64_t* shape; /// Size of each dimension DLDataType dtype; /// Data type of the array char** channel_names; /// Channel name list TODO: 'S', 'T', and other dimension can have names so need to be /// generalized. float* spacing; /// Physical size char** spacing_units; /// Units for each spacing element (size is same with `ndim`) float* origin; /// Physical location of (0, 0, 0) (size is always 3) float* direction; /// Direction cosines (size is always 3x3) const char* coord_sys; /// The coordinate frame in which the direction cosines are measured (either /// 'LPS'(ITK/DICOM) or 'RAS'(NIfTI/3D Slicer)) ResolutionInfoDesc resolution_info; /// Resolution information AssociatedImageInfoDesc associated_image_info; /// Associated image information const char* raw_data; /// Metadata in text format from the original image char* json_data; /// cucim & vendor's metadata in JSON format. Will be merged with above standard metadata. Memory /// for this needs to be released manually. }; // Without raw_data and json_data, metadata size is approximately 1104 bytes. // It might be good to allocate 4k for that. constexpr size_t IMAGE_METADATA_BUFFER_SIZE = 4096; class EXPORT_VISIBLE ImageMetadata { public: ImageMetadata(); ~ImageMetadata(); void* allocate(size_t size); std::pmr::monotonic_buffer_resource& get_resource(); constexpr uint8_t* get_buffer() { return buffer_.data(); } ImageMetadataDesc& desc(); ImageMetadata& ndim(uint16_t ndim); ImageMetadata& dims(std::string_view&& dims); ImageMetadata& shape(std::pmr::vector<int64_t>&& shape); ImageMetadata& dtype(const DLDataType& dtype); ImageMetadata& channel_names(std::pmr::vector<std::string_view>&& channel_names); ImageMetadata& spacing(std::pmr::vector<float>&& spacing); ImageMetadata& spacing_units(std::pmr::vector<std::string_view>&& spacing_units); ImageMetadata& origin(std::pmr::vector<float>&& origin); ImageMetadata& direction(std::pmr::vector<float>&& direction); ImageMetadata& coord_sys(std::string_view&& coord_sys); // ResolutionInfoDesc ImageMetadata& level_count(uint16_t level_count); ImageMetadata& level_ndim(uint16_t level_ndim); ImageMetadata& level_dimensions(std::pmr::vector<int64_t>&& level_dimensions); ImageMetadata& level_downsamples(std::pmr::vector<float>&& level_downsamples); ImageMetadata& level_tile_sizes(std::pmr::vector<uint32_t>&& level_tile_sizes); // AssociatedImageInfoDesc ImageMetadata& image_count(uint16_t image_count); ImageMetadata& image_names(std::pmr::vector<std::string_view>&& image_names); ImageMetadata& raw_data(const std::string_view& raw_data); ImageMetadata& json_data(const std::string_view& json_data); private: ImageMetadataDesc desc_{}; std::array<uint8_t, IMAGE_METADATA_BUFFER_SIZE> buffer_{}; std::pmr::monotonic_buffer_resource res_{ buffer_.data(), sizeof(buffer_) }; // manylinux2014 requires gcc4-compatible libstdcxx-abi(gcc is configured with // '--with-default-libstdcxx-abi=gcc4-compatible', https://gcc.gnu.org/onlinedocs/libstdc++/manual/configure.html) which // forces to set _GLIBCXX_USE_CXX11_ABI=0 so std::pmr::string wouldn't be available on CentOS 7. #if _GLIBCXX_USE_CXX11_ABI std::pmr::string dims_{ &res_ }; std::pmr::vector<int64_t> shape_{ &res_ }; std::pmr::vector<std::string_view> channel_names_{ &res_ }; std::pmr::vector<float> spacing_{ &res_ }; std::pmr::vector<std::string_view> spacing_units_{ &res_ }; std::pmr::vector<float> origin_{ &res_ }; std::pmr::vector<float> direction_{ &res_ }; std::pmr::string coord_sys_{ &res_ }; std::pmr::vector<int64_t> level_dimensions_{ &res_ }; std::pmr::vector<float> level_downsamples_{ &res_ }; std::pmr::vector<uint32_t> level_tile_sizes_{ &res_ }; std::pmr::vector<std::string_view> image_names_{ &res_ }; #else std::string dims_; std::pmr::vector<int64_t> shape_{ &res_ }; std::pmr::vector<std::string_view> channel_names_{ &res_ }; std::pmr::vector<float> spacing_{ &res_ }; std::pmr::vector<std::string_view> spacing_units_{ &res_ }; std::pmr::vector<float> origin_{ &res_ }; std::pmr::vector<float> direction_{ &res_ }; std::string coord_sys_; std::pmr::vector<int64_t> level_dimensions_{ &res_ }; std::pmr::vector<float> level_downsamples_{ &res_ }; std::pmr::vector<uint32_t> level_tile_sizes_{ &res_ }; std::pmr::vector<std::string_view> image_names_{ &res_ }; #endif // Memory for raw_data and json_data needs to be created with cucim_malloc(); }; struct ImageDataDesc { DLTensor container; char* shm_name; void* loader; }; struct ImageCheckerDesc { size_t header_start_offset; /// Start offset to look at the image header size_t header_read_size; /// Number of bytes from the start offset, needed to check image format /** * Returns true if the given file is valid for the format * @param file_name * @param buf * @param size * @return */ bool(CUCIM_ABI* is_valid)(const char* file_name, const char* buf, size_t size); }; struct ImageParserDesc { /** * * @param file_path * @return */ CuCIMFileHandle_share(CUCIM_ABI* open)(const char* file_path); /** * * @param handle * @param out_metadata * @return */ bool(CUCIM_ABI* parse)(CuCIMFileHandle_ptr handle, ImageMetadataDesc* out_metadata); /** * * @param handle * @return */ bool(CUCIM_ABI* close)(CuCIMFileHandle_ptr handle); }; struct ImageReaderRegionRequestDesc { int64_t* location = nullptr; void* location_unique = nullptr; int64_t* size = nullptr; void* size_unique = nullptr; uint64_t location_len = 1; int32_t size_ndim = 2; uint16_t level = 0; uint32_t num_workers = 0; uint32_t batch_size = 1; bool drop_last = false; uint32_t prefetch_factor = 2; bool shuffle = false; uint64_t seed = 0; DimIndicesDesc region_dim_indices{}; char* associated_image_name = nullptr; char* device = nullptr; DLTensor* buf = nullptr; char* shm_name = nullptr; }; struct ImageReaderDesc { /** * * @param handle * @param metadata * @param out_image_data * @param out_image_metadata needed for associated_image * @return */ bool(CUCIM_ABI* read)(const CuCIMFileHandle_ptr handle, const ImageMetadataDesc* metadata, const ImageReaderRegionRequestDesc* request, ImageDataDesc* out_image_data, ImageMetadataDesc* out_metadata); }; struct ImageWriterDesc { /** * * @param handle * @param metadata * @param image_data * @return */ bool(CUCIM_ABI* write)(const CuCIMFileHandle_ptr handle, const ImageMetadataDesc* metadata, const ImageDataDesc* image_data); }; struct ImageFormatDesc { void(CUCIM_ABI* set_enabled)(bool val); /// Sets if this format will be used in cucim (default: true). bool(CUCIM_ABI* is_enabled)(); /// true if this format is used when checking image compatibility. const char*(CUCIM_ABI* get_format_name)(); /// Returns the name of this format. ImageCheckerDesc image_checker; ImageParserDesc image_parser; ImageReaderDesc image_reader; ImageWriterDesc image_writer; }; struct IImageFormat { CUCIM_PLUGIN_INTERFACE("cucim::io::IImageFormat", 0, 1) ImageFormatDesc* formats; size_t format_count; }; } // namespace cucim::io::format #endif // CUCIM_IMAGE_FORMAT_H
0
rapidsai_public_repos/cucim/cpp
rapidsai_public_repos/cucim/cpp/tests/config.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * 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. */ #ifndef CUCIM_TESTS_CONFIG_H #define CUCIM_TESTS_CONFIG_H #include <string> #include <cstdlib> #define XSTR(x) STR(x) #define STR(x) #x struct AppConfig { std::string test_folder; std::string test_file; std::string temp_folder = "/tmp"; std::string get_input_path(const std::string default_value = "generated/tiff_stripe_4096x4096_256.tif") const { // If `test_file` is absolute path if (!test_folder.empty() && test_file.substr(0, 1) == "/") { return test_file; } else { std::string test_data_folder = test_folder; if (test_data_folder.empty()) { if (const char* env_p = std::getenv("CUCIM_TESTDATA_FOLDER")) { test_data_folder = env_p; } else { test_data_folder = "test_data"; } } if (test_file.empty()) { return test_data_folder + "/" + default_value; } else { return test_data_folder + "/" + test_file; } } } std::string get_plugin_path(const char* default_value = "cucim.kit.cuslide@" XSTR(CUCIM_VERSION) ".so") { std::string plugin_path = default_value; if (const char* env_p = std::getenv("CUCIM_TEST_PLUGIN_PATH")) { plugin_path = env_p; } return plugin_path; } }; extern AppConfig g_config; #endif // CUCIM_TESTS_CONFIG_H
0
rapidsai_public_repos/cucim/cpp
rapidsai_public_repos/cucim/cpp/tests/test_metadata.cpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * 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. */ #include "config.h" #include "cucim/cuimage.h" #include "cucim/logger/timer.h" #include "cucim/core/framework.h" #include "cucim/io/format/image_format.h" #include <catch2/catch_test_macros.hpp> #include <fmt/format.h> #include <chrono> #include <cstdlib> #include <memory> #include <fcntl.h> #include <unistd.h> #include <string_view> // Test #include <iostream> #include <fstream> #include <sys/stat.h> #include <sys/mman.h> #include <cuda_runtime.h> #define ALIGN_UP(x, align_to) (((uint64_t)(x) + ((uint64_t)(align_to)-1)) & ~((uint64_t)(align_to)-1)) #define CUDA_ERROR(stmt) \ { \ cuda_status = stmt; \ if (cudaSuccess != cuda_status) \ { \ INFO(fmt::format("Error message: {}", cudaGetErrorString(cuda_status))); \ REQUIRE(cudaSuccess == cuda_status); \ } \ } #define POSIX_ERROR(stmt) \ { \ err = stmt; \ if (err < 0) \ { \ INFO(fmt::format("Error message: {}", std::strerror(errno))); \ REQUIRE(err >= 0); \ } \ } class Document { bool is_cached_{}; double rank_{}; int id_{}; }; #include <string> void test(float* haha) { fmt::print("T {} {} {}\n", haha[0], haha[1], haha[2]); } TEST_CASE("Verify metadata", "[test_metadata.cpp]") { cucim::Framework* framework = cucim::acquire_framework("sample.app"); REQUIRE(framework != nullptr); std::string plugin_path = g_config.get_plugin_path(); cucim::io::format::IImageFormat* image_format = framework->acquire_interface_from_library<cucim::io::format::IImageFormat>(plugin_path.c_str()); // fmt::print("{}\n", image_format->formats[0].get_format_name()); REQUIRE(image_format != nullptr); std::string input_path = g_config.get_input_path(); std::shared_ptr<CuCIMFileHandle>* file_handle_shared = reinterpret_cast<std::shared_ptr<CuCIMFileHandle>*>( image_format->formats[0].image_parser.open(input_path.c_str())); std::shared_ptr<CuCIMFileHandle> file_handle = *file_handle_shared; delete file_handle_shared; // Set deleter to close the file handle file_handle->set_deleter(image_format->formats[0].image_parser.close); cucim::io::format::ImageMetadata metadata{}; image_format->formats[0].image_parser.parse(file_handle.get(), &metadata.desc()); // Using fmt::print() has a problem with TestMate VSCode plugin (output is not caught by the plugin) std::cout << fmt::format("metadata: {}\n", metadata.desc().raw_data); const uint8_t* buf = metadata.get_buffer(); const uint8_t* buf2 = static_cast<uint8_t*>(metadata.allocate(1)); std::cout << fmt::format("test: {}\n", buf2 - buf); // cucim::CuImage img{ g_config.get_input_path("private/philips_tiff_000.tif") }; // const auto& img_metadata = img.metadata(); // std::cout << fmt::format("metadata: {}\n", img_metadata); // auto v = img.spacing(); // std::cout << fmt::format("spacing: {}\n", v.size()); // delete ((cuslide::tiff::TIFF*)handle.client_data); // cucim_free(handle.client_data); // cucim_free(handle.client_data); // fmt::print("alignment: {}\n", alignof(int)); // fmt::print("Document: {}\n", sizeof(Document)); // fmt::print("max align: {}\n", alignof(size_t)); // auto a = std::string{ "" }; // fmt::print("size of ImageMetadataDesc :{}\n", sizeof(cucim::io::format::ImageMetadataDesc)); // fmt::print("size of ImageMetadata :{}\n", sizeof(cucim::io::format::ImageMetadata)); // cucim::io::format::ImageMetadata metadata; // test(std::array<float, 3>{ 1.0, 2.0, 3.0 }.data()); // std::vector<float> d(3); // fmt::print("metadata: {} \n", (size_t)std::addressof(metadata)); // fmt::print("handle: {} \n", (size_t)std::addressof(metadata.desc())); // fmt::print("ndim: {} \n", ((cucim::io::format::ImageMetadataDesc*)&metadata)->ndim); // // cucim::io::format::ImageMetadata a; // REQUIRE(1 == 1); } TEST_CASE("Load test", "[test_metadata.cpp]") { cucim::CuImage img{ g_config.get_input_path("private/philips_tiff_000.tif") }; REQUIRE(img.dtype() == DLDataType{ DLDataTypeCode::kDLUInt, 8, 1 }); REQUIRE(img.typestr() == "|u1"); auto test = img.read_region({ -10, -10 }, { 100, 100 }); REQUIRE(test.dtype() == DLDataType{ DLDataTypeCode::kDLUInt, 8, 1 }); REQUIRE(test.typestr() == "|u1"); fmt::print("{}", img.metadata()); }
0
rapidsai_public_repos/cucim/cpp
rapidsai_public_repos/cucim/cpp/tests/CMakeLists.txt
# # Copyright (c) 2020, NVIDIA CORPORATION. # 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. # include(CTest) enable_testing() ################################################################################ # Add executable: cucim_tests ################################################################################ add_executable(cucim_tests main.cpp test_read_region.cpp test_cufile.cpp test_metadata.cpp ) set_target_properties(cucim_tests PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO ) target_compile_features(cucim_tests PRIVATE ${CUCIM_REQUIRED_FEATURES}) # Use generator expression to avoid `nvcc fatal : Value '-std=c++17' is not defined for option 'Werror'` target_compile_options(cucim_tests PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-Werror -Wall -Wextra>) target_compile_definitions(cucim_tests PUBLIC CUCIM_VERSION=${PROJECT_VERSION} CUCIM_VERSION_MAJOR=${PROJECT_VERSION_MAJOR} CUCIM_VERSION_MINOR=${PROJECT_VERSION_MINOR} CUCIM_VERSION_PATCH=${PROJECT_VERSION_PATCH} CUCIM_VERSION_BUILD=${PROJECT_VERSION_BUILD} ) # Include pthread # (https://cmake.org/cmake/help/v3.18/module/FindThreads.html) set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads REQUIRED) target_link_libraries(cucim_tests PRIVATE CUDA::cudart ${CUCIM_PACKAGE_NAME} deps::catch2 deps::openslide deps::taskflow Threads::Threads # -lpthread ) include(Catch) # See https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#catchcmake-and-catchaddtestscmake for other options catch_discover_tests(cucim_tests)
0
rapidsai_public_repos/cucim/cpp
rapidsai_public_repos/cucim/cpp/tests/test_read_region.cpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * 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. */ #include <chrono> #include <iostream> #include <catch2/catch_test_macros.hpp> #include <cuda_runtime.h> #include <openslide/openslide.h> #include "config.h" #include "cucim/core/framework.h" #include "cucim/io/device.h" #include "cucim/io/format/image_format.h" #include "cucim/memory/memory_manager.h" SCENARIO("Verify read_region()", "[test_read_region.cpp]") { constexpr int test_sx = 200; constexpr int test_sy = 300; constexpr int test_width = 3; constexpr int test_height = 2; for (int iter=0; iter< 100; iter++) { auto start = std::chrono::high_resolution_clock::now(); std::string input_path = g_config.get_input_path(); openslide_t* slide = openslide_open(input_path.c_str()); REQUIRE(slide != nullptr); auto buf = static_cast<uint32_t*>(cucim_malloc(test_width * test_height * 4)); int64_t w, h; openslide_get_level0_dimensions(slide, &w, &h); printf("w = %ld h=%ld\n", w, h); openslide_read_region(slide, buf, test_sx, test_sy, 0, test_width, test_height); auto out_image = reinterpret_cast<uint8_t*>(buf); int hash = 0; for(int i = 0 ;i < test_width * test_height * 4; i+= 4) { hash += out_image[i] + out_image[i+1] + out_image[i+2]; printf("%d %d %d ", out_image[i + 2], out_image[i+1], out_image[i]); } printf("\nopenslide count: %d\n", hash); cucim_free(buf); openslide_close(slide); auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); printf("time:%f\n", elapsed_seconds.count()); } printf("\n\n"); cucim::Framework* framework = cucim::acquire_framework("sample.app"); //TODO: Parameterize input library/image cucim::io::format::IImageFormat* image_format = framework->acquire_interface_from_library<cucim::io::format::IImageFormat>(g_config.get_plugin_path().c_str()); if (!image_format) { throw std::runtime_error("Cannot load plugin!"); } std::cout << image_format->formats[0].get_format_name() << std::endl; for (int iter=0; iter< 100; iter++) { auto start = std::chrono::high_resolution_clock::now(); std::string input_path = g_config.get_input_path(); std::shared_ptr<CuCIMFileHandle>* file_handle_shared = reinterpret_cast<std::shared_ptr<CuCIMFileHandle>*>( image_format->formats[0].image_parser.open(input_path.c_str())); std::shared_ptr<CuCIMFileHandle> file_handle = *file_handle_shared; delete file_handle_shared; // Set deleter to close the file handle file_handle->set_deleter(image_format->formats[0].image_parser.close); cucim::io::format::ImageMetadata metadata{}; image_format->formats[0].image_parser.parse(file_handle.get(), &metadata.desc()); cucim::io::format::ImageReaderRegionRequestDesc request{}; int64_t request_location[2] = { test_sx, test_sy }; request.location = request_location; request.level = 0; int64_t request_size[2] = { test_width, test_height }; request.size = request_size; request.device = const_cast<char*>("cpu"); cucim::io::format::ImageDataDesc image_data{}; image_format->formats[0].image_reader.read( file_handle.get(), &metadata.desc(), &request, &image_data, nullptr /*out_metadata*/); auto out_image = reinterpret_cast<uint8_t*>(image_data.container.data); int hash = 0; for (int i = 0; i < test_width * test_height * 3; i += 3) { hash += out_image[i] + out_image[i + 1] + out_image[i + 2]; printf("%d %d %d ", out_image[i], out_image[i + 1], out_image[i + 2]); } printf("\ncucim count: %d\n", hash); // for (int i = 0; i < test_width * test_height * 4; i += 4) // { // hash += out_image[i] + out_image[i + 1] + out_image[i + 2]; // printf("%d %d %d ", out_image[i], out_image[i + 1], out_image[i + 2]); // } printf("\ncucim count: %d\n", hash); cucim_free(image_data.container.data); if (image_data.container.shape) { cucim_free(image_data.container.shape); image_data.container.shape = nullptr; } if (image_data.container.strides) { cucim_free(image_data.container.strides); image_data.container.strides = nullptr; } if (image_data.shm_name) { cucim_free(image_data.shm_name); image_data.shm_name = nullptr; } auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); printf("time2:%f\n", elapsed_seconds.count()); } REQUIRE(3 == 3); }
0
rapidsai_public_repos/cucim/cpp
rapidsai_public_repos/cucim/cpp/tests/main.cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ // #define CATCH_CONFIG_MAIN // #include <catch2/catch_test_macros.hpp> // Implement main explicitly to handle additional parameters. #define CATCH_CONFIG_RUNNER #include "config.h" #include "cucim/core/framework.h" #include <catch2/catch_test_macros.hpp> #include <catch2/catch_session.hpp> #include <string> #include <fmt/format.h> CUCIM_FRAMEWORK_GLOBALS("sample.app") // Global config object AppConfig g_config; /** * Extract `--[option]` or `--[option]=` string from command and set the value to g_config object. * * @param argc number of arguments used for command * @param argv arguments for command * @param obj object reference to modify * @param argument name of argument(option) * @return true if it extracted the value for the option */ static bool extract_test_file_option(int* argc, char** argv, std::string& obj, const char* argument) { std::string arg_str = fmt::format("--{}=", argument); // test_file => --test_file= std::string arg_str2 = fmt::format("--{}", argument); // test_file => --test_file char* value_ptr = nullptr; for (int i = 1; argc && i < *argc; ++i) { if (strncmp(argv[i], arg_str.c_str(), arg_str.size()) == 0) { value_ptr = &argv[i][12]; for (int j = i + 1; argc && j < *argc; ++j) { argv[j - 1] = argv[j]; } --(*argc); argv[*argc] = nullptr; break; } if (strncmp(argv[i], arg_str2.c_str(), arg_str2.size()) == 0 && i + 1 < *argc) { value_ptr = argv[i + 1]; for (int j = i + 2; argc && j < *argc; ++j) { argv[j - 2] = argv[j]; } *argc -= 2; argv[*argc] = nullptr; argv[*argc + 1] = nullptr; break; } } if (value_ptr) { obj = value_ptr; return true; } else { return false; } } int main (int argc, char** argv) { extract_test_file_option(&argc, argv, g_config.test_folder, "test_folder"); extract_test_file_option(&argc, argv, g_config.test_file, "test_file"); extract_test_file_option(&argc, argv, g_config.temp_folder, "temp_folder"); printf("Target test folder: %s (use --test_folder option to change this)\n", g_config.test_folder.c_str()); printf("Target test file : %s (use --test_file option to change this)\n", g_config.test_file.c_str()); printf("Temp folder : %s (use --temp_folder option to change this)\n", g_config.temp_folder.c_str()); int result = Catch::Session().run(argc, argv); return result; }
0
rapidsai_public_repos/cucim/cpp
rapidsai_public_repos/cucim/cpp/tests/test_cufile.cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #include "cucim/logger/timer.h" #include "config.h" #include <catch2/catch_test_macros.hpp> #include <fmt/format.h> #include <cucim/filesystem/cufile_driver.h> #include <chrono> #include <cstdlib> #include <fcntl.h> #include <unistd.h> #include <string_view> // Test #include <iostream> #include <fstream> #include <sys/stat.h> #include <sys/mman.h> #include <cuda_runtime.h> #define ALIGN_UP(x, align_to) (((uint64_t)(x) + ((uint64_t)(align_to)-1)) & ~((uint64_t)(align_to)-1)) #define CUDA_ERROR(stmt) \ { \ cuda_status = stmt; \ if (cudaSuccess != cuda_status) \ { \ INFO(fmt::format("Error message: {}", cudaGetErrorString(cuda_status))); \ REQUIRE(cudaSuccess == cuda_status); \ } \ } #define POSIX_ERROR(stmt) \ { \ err = stmt; \ if (err < 0) \ { \ INFO(fmt::format("Error message: {}", std::strerror(errno))); \ REQUIRE(err >= 0); \ } \ } static void create_test_file(const char* file_name, int size) { int fd = open(file_name, O_RDWR | O_CREAT | O_TRUNC, 0666); char test_data[size]; ::srand(0); for (int i = 0; i < size; i++) { test_data[i] = ::rand() % 256; // or i % 256; } ssize_t write_cnt = write(fd, test_data, size); (void)write_cnt; assert(write_cnt == size); close(fd); } TEST_CASE("Verify libcufile usage", "[test_cufile.cpp]") { cudaError_t cuda_status; int err; constexpr int BLOCK_SECTOR_SIZE = 4096; constexpr char const* test_w_flags[] = { "wpn", "wp", "wn", "w" }; constexpr char const* test_flags_desc[] = { "regular file", "o_direct", "gds with no O_DIRECT", "gds with O_DIRECT" }; constexpr int W_FLAG_LEN = sizeof(test_w_flags) / sizeof(test_w_flags[0]); constexpr char const* test_r_flags[] = { "rpn", "rp", "rn", "r" }; // clang-format off constexpr int test_buf_offsets[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; constexpr int test_file_offsets[] = { 0, 500, 0, 0, 400, 400, 4000, 4500, 4500, 4096 * 2 - 1 }; constexpr int test_counts[] = { 0, 0, 500, 4097, 500, 4097, 500, 500, 4097, 500 }; // clang-format on constexpr int TEST_PARAM_LEN = sizeof(test_counts) / sizeof(test_counts[0]); uint8_t test_data[BLOCK_SECTOR_SIZE * 3]; std::string output_file = fmt::format("{}/test_cufile.raw", g_config.temp_folder); ::srand(777); for (int i = 0; i < BLOCK_SECTOR_SIZE * 3; i++) { test_data[i] = ::rand() % 256; // or (BLOCK_SECTOR_SIZE * 3 - i) % 256; } std::hash<std::string_view> str_hash; for (int test_param_index = 0; test_param_index < TEST_PARAM_LEN; ++test_param_index) { int test_buf_offset = test_buf_offsets[test_param_index]; int test_file_offset = test_file_offsets[test_param_index]; int test_count = test_counts[test_param_index]; // Allocate memory uint8_t* unaligned_host = static_cast<uint8_t*>(malloc(test_count + test_buf_offset)); uint8_t* aligned_host; POSIX_ERROR(posix_memalign(reinterpret_cast<void**>(&aligned_host), 512, test_count + test_buf_offset)); uint8_t* unaligned_device; CUDA_ERROR(cudaMalloc(&unaligned_device, test_count + test_buf_offset + BLOCK_SECTOR_SIZE)); uint8_t* aligned_device = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_device, BLOCK_SECTOR_SIZE)); uint8_t* unaligned_device_host; CUDA_ERROR(cudaMallocHost(&unaligned_device_host, test_count + test_buf_offset + BLOCK_SECTOR_SIZE)); uint8_t* aligned_device_host = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_device_host, BLOCK_SECTOR_SIZE)); uint8_t* unaligned_device_managed; CUDA_ERROR(cudaMallocManaged(&unaligned_device_managed, test_count + test_buf_offset + BLOCK_SECTOR_SIZE)); uint8_t* aligned_device_managed = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_device_managed, BLOCK_SECTOR_SIZE)); SECTION(fmt::format("Write Test with different parameters (offset:{}, count:{})", test_file_offset, test_count)) { { INFO("# unaligned_host"); size_t reference_whole_hash = 0; size_t reference_hash = 0; ssize_t reference_write_cnt = 0; ssize_t reference_read_cnt = 0; for (int flag_idx = 0; flag_idx < W_FLAG_LEN; ++flag_idx) { INFO(fmt::format("flag_index: {} ({})\n count: {}\n file_offset: {} buf_offset: {}\n", flag_idx, test_flags_desc[flag_idx], test_count, test_file_offset, test_buf_offset)); { INFO(fmt::format("memory: unaligned_host \n")); create_test_file(output_file.c_str(), BLOCK_SECTOR_SIZE * 3); auto fd = cucim::filesystem::open(output_file.c_str(), test_w_flags[flag_idx]); memcpy(unaligned_host + test_buf_offset, test_data, test_count); ssize_t write_cnt = fd->pwrite(unaligned_host, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_write_cnt = write_cnt; } else { REQUIRE(write_cnt == reference_write_cnt); } fd = cucim::filesystem::open(output_file.c_str(), test_r_flags[flag_idx]); memset(unaligned_host, 0, test_count + test_buf_offset); ssize_t read_cnt = fd->pread(unaligned_host, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_read_cnt = read_cnt; } else { REQUIRE(read_cnt == reference_read_cnt); } size_t posix_hash = str_hash(std::string_view((char*)unaligned_host + test_buf_offset, read_cnt)); char file_data[BLOCK_SECTOR_SIZE * 4]{}; int fd2 = open(output_file.c_str(), O_RDONLY); read_cnt = read(fd2, file_data, BLOCK_SECTOR_SIZE * 4); size_t file_hash = str_hash(std::string_view(file_data, read_cnt)); if (flag_idx == 0) { reference_hash = posix_hash; reference_whole_hash = file_hash; } else { REQUIRE(reference_hash == posix_hash); REQUIRE(reference_whole_hash == file_hash); } } } } { INFO("# aligned_host"); size_t reference_whole_hash = 0; size_t reference_hash = 0; ssize_t reference_write_cnt = 0; ssize_t reference_read_cnt = 0; for (int flag_idx = 0; flag_idx < W_FLAG_LEN; ++flag_idx) { INFO(fmt::format("flag_index: {} ({})\n count: {}\n file_offset: {} buf_offset: {}\n", flag_idx, test_flags_desc[flag_idx], test_count, test_file_offset, test_buf_offset)); { INFO(fmt::format("memory: aligned_host \n")); create_test_file(output_file.c_str(), BLOCK_SECTOR_SIZE * 3); auto fd = cucim::filesystem::open(output_file.c_str(), test_w_flags[flag_idx]); memcpy(aligned_host + test_buf_offset, test_data, test_count + test_buf_offset); ssize_t write_cnt = fd->pwrite(aligned_host, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_write_cnt = write_cnt; } else { REQUIRE(write_cnt == reference_write_cnt); } fd = cucim::filesystem::open(output_file.c_str(), test_r_flags[flag_idx]); memset(aligned_host, 0, test_count + test_buf_offset); ssize_t read_cnt = fd->pread(aligned_host, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_read_cnt = read_cnt; } else { REQUIRE(read_cnt == reference_read_cnt); } size_t posix_hash = str_hash(std::string_view((char*)aligned_host + test_buf_offset, read_cnt)); char file_data[BLOCK_SECTOR_SIZE * 4]{}; int fd2 = open(output_file.c_str(), O_RDONLY); read_cnt = read(fd2, file_data, BLOCK_SECTOR_SIZE * 4); size_t file_hash = str_hash(std::string_view(file_data, read_cnt)); if (flag_idx == 0) { reference_hash = posix_hash; reference_whole_hash = file_hash; } else { REQUIRE(reference_hash == posix_hash); REQUIRE(reference_whole_hash == file_hash); } } } } { // Device Memory { INFO("# unaligned_device"); size_t reference_whole_hash = 0; size_t reference_hash = 0; ssize_t reference_write_cnt = 0; ssize_t reference_read_cnt = 0; for (int flag_idx = 0; flag_idx < W_FLAG_LEN; ++flag_idx) { INFO(fmt::format("flag_index: {} ({})\n count: {}\n file_offset: {} buf_offset: {}\n", flag_idx, test_flags_desc[flag_idx], test_count, test_file_offset, test_buf_offset)); { INFO(fmt::format("memory: unaligned_device \n")); create_test_file(output_file.c_str(), BLOCK_SECTOR_SIZE * 3); auto fd = cucim::filesystem::open(output_file.c_str(), test_w_flags[flag_idx]); cudaMemcpy(unaligned_device + test_buf_offset, test_data, test_count, cudaMemcpyHostToDevice); ssize_t write_cnt = fd->pwrite(unaligned_device, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_write_cnt = write_cnt; } else { REQUIRE(write_cnt == reference_write_cnt); } fd = cucim::filesystem::open(output_file.c_str(), test_r_flags[flag_idx]); cudaMemset(unaligned_device, 0, test_count + test_buf_offset); ssize_t read_cnt = fd->pread(unaligned_device, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_read_cnt = read_cnt; } else { REQUIRE(read_cnt == reference_read_cnt); } cudaMemcpy(unaligned_host, unaligned_device, test_count, cudaMemcpyDeviceToHost); size_t posix_hash = str_hash(std::string_view((char*)unaligned_host + test_buf_offset, read_cnt)); char file_data[BLOCK_SECTOR_SIZE * 4]{}; int fd2 = open(output_file.c_str(), O_RDONLY); read_cnt = read(fd2, file_data, BLOCK_SECTOR_SIZE * 4); size_t file_hash = str_hash(std::string_view(file_data, read_cnt)); if (flag_idx == 0) { reference_hash = posix_hash; reference_whole_hash = file_hash; } else { REQUIRE(reference_hash == posix_hash); REQUIRE(reference_whole_hash == file_hash); } } } } { INFO("# aligned_device"); size_t reference_whole_hash = 0; size_t reference_hash = 0; ssize_t reference_write_cnt = 0; ssize_t reference_read_cnt = 0; for (int flag_idx = 0; flag_idx < W_FLAG_LEN; ++flag_idx) { INFO(fmt::format("flag_index: {} ({})\n count: {}\n file_offset: {} buf_offset: {}\n", flag_idx, test_flags_desc[flag_idx], test_count, test_file_offset, test_buf_offset)); { INFO(fmt::format("memory: aligned_device \n")); create_test_file(output_file.c_str(), BLOCK_SECTOR_SIZE * 3); auto fd = cucim::filesystem::open(output_file.c_str(), test_w_flags[flag_idx]); cudaMemcpy(aligned_device + test_buf_offset, test_data, test_count, cudaMemcpyHostToDevice); ssize_t write_cnt = fd->pwrite(aligned_device, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_write_cnt = write_cnt; } else { REQUIRE(write_cnt == reference_write_cnt); } fd = cucim::filesystem::open(output_file.c_str(), test_r_flags[flag_idx]); cudaMemset(aligned_device, 0, test_count + test_buf_offset); ssize_t read_cnt = fd->pread(aligned_device, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_read_cnt = read_cnt; } else { REQUIRE(read_cnt == reference_read_cnt); } cudaMemcpy(aligned_host, aligned_device, test_count, cudaMemcpyDeviceToHost); size_t posix_hash = str_hash(std::string_view((char*)aligned_host + test_buf_offset, read_cnt)); char file_data[BLOCK_SECTOR_SIZE * 4]{}; int fd2 = open(output_file.c_str(), O_RDONLY); read_cnt = read(fd2, file_data, BLOCK_SECTOR_SIZE * 4); size_t file_hash = str_hash(std::string_view(file_data, read_cnt)); if (flag_idx == 0) { reference_hash = posix_hash; reference_whole_hash = file_hash; } else { REQUIRE(reference_hash == posix_hash); REQUIRE(reference_whole_hash == file_hash); } } } } // Pinned Host Memory { INFO("# unaligned_device (pinned host)"); size_t reference_whole_hash = 0; size_t reference_hash = 0; ssize_t reference_write_cnt = 0; ssize_t reference_read_cnt = 0; for (int flag_idx = 0; flag_idx < W_FLAG_LEN; ++flag_idx) { INFO(fmt::format("flag_index: {} ({})\n count: {}\n file_offset: {} buf_offset: {}\n", flag_idx, test_flags_desc[flag_idx], test_count, test_file_offset, test_buf_offset)); { INFO(fmt::format("memory: unaligned_device (pinned host)\n")); create_test_file(output_file.c_str(), BLOCK_SECTOR_SIZE * 3); auto fd = cucim::filesystem::open(output_file.c_str(), test_w_flags[flag_idx]); cudaMemcpy( unaligned_device_host + test_buf_offset, test_data, test_count, cudaMemcpyHostToDevice); ssize_t write_cnt = fd->pwrite(unaligned_device_host, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_write_cnt = write_cnt; } else { REQUIRE(write_cnt == reference_write_cnt); } fd = cucim::filesystem::open(output_file.c_str(), test_r_flags[flag_idx]); cudaMemset(unaligned_device_host, 0, test_count + test_buf_offset); ssize_t read_cnt = fd->pread(unaligned_device_host, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_read_cnt = read_cnt; } else { REQUIRE(read_cnt == reference_read_cnt); } cudaMemcpy(unaligned_host, unaligned_device_host, test_count, cudaMemcpyDeviceToHost); size_t posix_hash = str_hash(std::string_view((char*)unaligned_host + test_buf_offset, read_cnt)); char file_data[BLOCK_SECTOR_SIZE * 4]{}; int fd2 = open(output_file.c_str(), O_RDONLY); read_cnt = read(fd2, file_data, BLOCK_SECTOR_SIZE * 4); size_t file_hash = str_hash(std::string_view(file_data, read_cnt)); if (flag_idx == 0) { reference_hash = posix_hash; reference_whole_hash = file_hash; } else { REQUIRE(reference_hash == posix_hash); REQUIRE(reference_whole_hash == file_hash); } } } } { INFO("# aligned_device (pinned host)"); size_t reference_whole_hash = 0; size_t reference_hash = 0; ssize_t reference_write_cnt = 0; ssize_t reference_read_cnt = 0; for (int flag_idx = 0; flag_idx < W_FLAG_LEN; ++flag_idx) { INFO(fmt::format("flag_index: {} ({})\n count: {}\n file_offset: {} buf_offset: {}\n", flag_idx, test_flags_desc[flag_idx], test_count, test_file_offset, test_buf_offset)); { INFO(fmt::format("memory: aligned_device (pinned host)\n")); create_test_file(output_file.c_str(), BLOCK_SECTOR_SIZE * 3); auto fd = cucim::filesystem::open(output_file.c_str(), test_w_flags[flag_idx]); cudaMemcpy( aligned_device_host + test_buf_offset, test_data, test_count, cudaMemcpyHostToDevice); ssize_t write_cnt = fd->pwrite(aligned_device_host, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_write_cnt = write_cnt; } else { REQUIRE(write_cnt == reference_write_cnt); } fd = cucim::filesystem::open(output_file.c_str(), test_r_flags[flag_idx]); cudaMemset(aligned_device_host, 0, test_count + test_buf_offset); ssize_t read_cnt = fd->pread(aligned_device_host, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_read_cnt = read_cnt; } else { REQUIRE(read_cnt == reference_read_cnt); } cudaMemcpy(aligned_host, aligned_device_host, test_count, cudaMemcpyDeviceToHost); size_t posix_hash = str_hash(std::string_view((char*)aligned_host + test_buf_offset, read_cnt)); char file_data[BLOCK_SECTOR_SIZE * 4]{}; int fd2 = open(output_file.c_str(), O_RDONLY); read_cnt = read(fd2, file_data, BLOCK_SECTOR_SIZE * 4); size_t file_hash = str_hash(std::string_view(file_data, read_cnt)); if (flag_idx == 0) { reference_hash = posix_hash; reference_whole_hash = file_hash; } else { REQUIRE(reference_hash == posix_hash); REQUIRE(reference_whole_hash == file_hash); } } } } // ManageDevice Memory { INFO("# unaligned_device (managed)"); size_t reference_whole_hash = 0; size_t reference_hash = 0; ssize_t reference_write_cnt = 0; ssize_t reference_read_cnt = 0; for (int flag_idx = 0; flag_idx < W_FLAG_LEN; ++flag_idx) { INFO(fmt::format("flag_index: {} ({})\n count: {}\n file_offset: {} buf_offset: {}\n", flag_idx, test_flags_desc[flag_idx], test_count, test_file_offset, test_buf_offset)); { INFO(fmt::format("memory: unaligned_device (managed)\n")); create_test_file(output_file.c_str(), BLOCK_SECTOR_SIZE * 3); auto fd = cucim::filesystem::open(output_file.c_str(), test_w_flags[flag_idx]); cudaMemcpy(unaligned_device_managed + test_buf_offset, test_data, test_count, cudaMemcpyHostToDevice); ssize_t write_cnt = fd->pwrite(unaligned_device_managed, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_write_cnt = write_cnt; } else { REQUIRE(write_cnt == reference_write_cnt); } fd = cucim::filesystem::open(output_file.c_str(), test_r_flags[flag_idx]); cudaMemset(unaligned_device_managed, 0, test_count + test_buf_offset); ssize_t read_cnt = fd->pread(unaligned_device_managed, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_read_cnt = read_cnt; } else { REQUIRE(read_cnt == reference_read_cnt); } cudaMemcpy(unaligned_host, unaligned_device_managed, test_count, cudaMemcpyDeviceToHost); size_t posix_hash = str_hash(std::string_view((char*)unaligned_host + test_buf_offset, read_cnt)); char file_data[BLOCK_SECTOR_SIZE * 4]{}; int fd2 = open(output_file.c_str(), O_RDONLY); read_cnt = read(fd2, file_data, BLOCK_SECTOR_SIZE * 4); size_t file_hash = str_hash(std::string_view(file_data, read_cnt)); if (flag_idx == 0) { reference_hash = posix_hash; reference_whole_hash = file_hash; } else { REQUIRE(reference_hash == posix_hash); REQUIRE(reference_whole_hash == file_hash); } } } } { INFO("# aligned_device (managed)"); size_t reference_whole_hash = 0; size_t reference_hash = 0; ssize_t reference_write_cnt = 0; ssize_t reference_read_cnt = 0; for (int flag_idx = 0; flag_idx < W_FLAG_LEN; ++flag_idx) { INFO(fmt::format("flag_index: {} ({})\n count: {}\n file_offset: {} buf_offset: {}\n", flag_idx, test_flags_desc[flag_idx], test_count, test_file_offset, test_buf_offset)); { INFO(fmt::format("memory: aligned_device (managed)\n")); create_test_file(output_file.c_str(), BLOCK_SECTOR_SIZE * 3); auto fd = cucim::filesystem::open(output_file.c_str(), test_w_flags[flag_idx]); cudaMemcpy(aligned_device_managed + test_buf_offset, test_data, test_count, cudaMemcpyHostToDevice); ssize_t write_cnt = fd->pwrite(aligned_device_managed, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_write_cnt = write_cnt; } else { REQUIRE(write_cnt == reference_write_cnt); } fd = cucim::filesystem::open(output_file.c_str(), test_r_flags[flag_idx]); cudaMemset(aligned_device_managed, 0, test_count + test_buf_offset); ssize_t read_cnt = fd->pread(aligned_device_managed, test_count, test_file_offset, test_buf_offset); if (flag_idx == 0) { reference_read_cnt = read_cnt; } else { REQUIRE(read_cnt == reference_read_cnt); } cudaMemcpy(aligned_host, aligned_device_managed, test_count, cudaMemcpyDeviceToHost); size_t posix_hash = str_hash(std::string_view((char*)aligned_host + test_buf_offset, read_cnt)); char file_data[BLOCK_SECTOR_SIZE * 4]{}; int fd2 = open(output_file.c_str(), O_RDONLY); read_cnt = read(fd2, file_data, BLOCK_SECTOR_SIZE * 4); size_t file_hash = str_hash(std::string_view(file_data, read_cnt)); if (flag_idx == 0) { reference_hash = posix_hash; reference_whole_hash = file_hash; } else { REQUIRE(reference_hash == posix_hash); REQUIRE(reference_whole_hash == file_hash); } } } } } } CUDA_ERROR(cudaFree(unaligned_device)); CUDA_ERROR(cudaFreeHost(unaligned_device_host)); CUDA_ERROR(cudaFree(unaligned_device_managed)); free(aligned_host); free(unaligned_host); } }
0
rapidsai_public_repos/cucim/cpp/plugins
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/CMakeLists.txt
# Apache License, Version 2.0 # Copyright 2021 NVIDIA Corporation # # 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. # CUDA_STANDARD 17 is supported from CMAKE 3.18 # : https://cmake.org/cmake/help/v3.18/prop_tgt/CUDA_STANDARD.html cmake_minimum_required(VERSION 3.18) ################################################################################ # Prerequisite statements ################################################################################ # Set VERSION unset(VERSION CACHE) file(STRINGS ${CMAKE_CURRENT_LIST_DIR}/../../../VERSION VERSION) # strip alpha version info string(REGEX REPLACE "a.*$" "" VERSION ${VERSION}) # Append local cmake module path list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake/modules") project(cumed VERSION ${VERSION} DESCRIPTION "cumed" LANGUAGES CXX) set(CUCIM_PLUGIN_NAME "cucim.kit.cumed") ################################################################################ # Include utilities ################################################################################ include(SuperBuildUtils) include(CuCIMUtils) ################################################################################ # Set cmake policy ################################################################################ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.19") cmake_policy(SET CMP0110 NEW) # For add_test() to support arbitrary characters in test name endif() ################################################################################ # Basic setup ################################################################################ # Set default build type set(DEFAULT_BUILD_TYPE "Release") if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to '${DEFAULT_BUILD_TYPE}' as none was specified.") set(CMAKE_BUILD_TYPE "${DEFAULT_BUILD_TYPE}" CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif () # Set default output directories if (NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib") endif() if (NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib") endif() if (NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin") endif() # Find CUDAToolkit as rmm depends on it find_package(CUDAToolkit REQUIRED) # For Threads::Threads find_package(Threads REQUIRED) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED YES) # Include CUDA headers explicitly for VSCode intelli-sense include_directories(AFTER SYSTEM ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) # Disable visibility to not expose unnecessary symbols set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN YES) # Set RPATH if (NOT APPLE) set(CMAKE_INSTALL_RPATH $ORIGIN) endif() # Set Installation setup if (NOT CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX ${CMAKE_CURRENT_LIST_DIR}/install) # CACHE PATH "install here" FORCE) endif () include(GNUInstallDirs) # Force to set CMAKE_INSTALL_LIBDIR to lib as the library can be built with Cent OS ('lib64' is set) and # /usr/local/lib64 or /usr/local/lib is not part of ld.so.conf* (`cat /etc/ld.so.conf.d/* | grep lib64`) # https://gitlab.kitware.com/cmake/cmake/-/issues/20565 set(CMAKE_INSTALL_LIBDIR lib) include(ExternalProject) ################################################################################ # Options ################################################################################ # Setup CXX11 ABI # : Adds CXX11 ABI definition to the compiler command line for targets in the current directory, # whether added before or after this command is invoked, and for the ones in sub-directories added after. add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0) # TODO: create two library, one with CXX11 ABI and one without it. ################################################################################ # Define dependencies ################################################################################ superbuild_depend(fmt) superbuild_depend(catch2) superbuild_depend(googletest) superbuild_depend(googlebenchmark) superbuild_depend(cli11) ################################################################################ # Find cucim package ################################################################################ if (NOT CUCIM_SDK_PATH) get_filename_component(CUCIM_SDK_PATH "${CMAKE_SOURCE_DIR}/../../.." ABSOLUTE) message("CUCIM_SDK_PATH is not set. Using '${CUCIM_SDK_PATH}'") else() message("CUCIM_SDK_PATH is set to ${CUCIM_SDK_PATH}") endif() find_package(cucim CONFIG REQUIRED HINTS ${CUCIM_SDK_PATH}/install/${CMAKE_INSTALL_LIBDIR}/cmake/cucim $ENV{PREFIX}/include/cmake/cucim # In case conda build is used ) ################################################################################ # Define compile options ################################################################################ if(NOT BUILD_SHARED_LIBS) set(BUILD_SHARED_LIBS ON) endif() ################################################################################ # Add library: cucim ################################################################################ # Add library add_library(${CUCIM_PLUGIN_NAME} src/cumed/cumed.cpp src/cumed/cumed.h ) # Compile options set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO SOVERSION ${PROJECT_VERSION_MAJOR} VERSION ${PROJECT_VERSION} ) target_compile_features(${CUCIM_PLUGIN_NAME} PRIVATE cxx_std_17) # Use generator expression to avoid `nvcc fatal : Value '-std=c++17' is not defined for option 'Werror'` target_compile_options(${CUCIM_PLUGIN_NAME} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-Werror -Wall -Wextra>) # Link libraries target_link_libraries(${CUCIM_PLUGIN_NAME} PRIVATE CUDA::cudart deps::fmt cucim::cucim ) target_include_directories(${CUCIM_PLUGIN_NAME} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src # turbojpeg.h is not included in 'turbojpeg-static' so manually include ${deps-libjpeg-turbo_SOURCE_DIR} ) # Do not generate SONAME as this would be used as plugin # Need to use IMPORTED_NO_SONAME when using this .so file. set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES NO_SONAME 1) # Prevent relative path problem of .so with no DT_SONAME. # : https://stackoverflow.com/questions/27261288/cmake-linking-shared-c-object-from-externalproject-produces-binaries-with-rel target_link_options(${CUCIM_PLUGIN_NAME} PRIVATE "LINKER:-soname=${CUCIM_PLUGIN_NAME}@${PROJECT_VERSION}.so") # Do not add 'lib' prefix for the library set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES PREFIX "") # Postfix version set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES OUTPUT_NAME "${CUCIM_PLUGIN_NAME}@${PROJECT_VERSION}") ################################################################################ # Add tests #########################################################std####################### add_subdirectory(tests) add_subdirectory(benchmarks) ################################################################################ # Install ################################################################################ set(INSTALL_TARGETS ${CUCIM_PLUGIN_NAME} cumed_tests cumed_benchmarks ) install(TARGETS ${INSTALL_TARGETS} EXPORT ${CUCIM_PLUGIN_NAME}-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT ${CUCIM_PLUGIN_NAME}_Runtime LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${CUCIM_PLUGIN_NAME}_Runtime NAMELINK_COMPONENT ${CUCIM_PLUGIN_NAME}_Development ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${CUCIM_PLUGIN_NAME}_Development ) # Currently cumed plugin doesn't have include path so comment out # install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(EXPORT ${CUCIM_PLUGIN_NAME}-targets FILE ${CUCIM_PLUGIN_NAME}-targets.cmake NAMESPACE ${PROJECT_NAME}:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME}) # Write package configs include(CMakePackageConfigHelpers) configure_package_config_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME} ) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config-version.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config-version.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME} ) set(CMAKE_EXPORT_PACKAGE_REGISTRY ON) export(PACKAGE ${CUCIM_PLUGIN_NAME}) # Write package configs include(CMakePackageConfigHelpers) configure_package_config_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME} ) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config-version.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config-version.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME} ) set(CMAKE_EXPORT_PACKAGE_REGISTRY ON) # TODO: duplicate? export(PACKAGE ${CUCIM_PLUGIN_NAME}) unset(BUILD_SHARED_LIBS CACHE)
0
rapidsai_public_repos/cucim/cpp/plugins
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.editorconfig
[*] indent_style = space indent_size = 4 charset = utf-8 trim_trailing_whitespace = true max_line_length = 120 insert_final_newline = true
0
rapidsai_public_repos/cucim/cpp/plugins
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.clang-format
AccessModifierOffset: -4 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlinesLeft: false AlignTrailingComments: false AllowAllParametersOfDeclarationOnNextLine: true AllowShortFunctionsOnASingleLine: false AllowShortIfStatementsOnASingleLine: false AllowShortCaseLabelsOnASingleLine : false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakBeforeMultilineStrings: true AlwaysBreakTemplateDeclarations: true BinPackArguments: true BinPackParameters: false BreakBeforeBinaryOperators: false BreakBeforeBraces: Custom BraceWrapping: AfterClass: true AfterControlStatement: true AfterEnum: true AfterFunction: true AfterNamespace: true AfterObjCDeclaration: true AfterStruct: true AfterUnion: true AfterExternBlock: true BeforeCatch: true BeforeElse: true IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace : true BreakBeforeTernaryOperators: false BreakConstructorInitializersBeforeComma: false BreakStringLiterals: false ColumnLimit: 120 CommentPragmas: '' ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: false DerivePointerBinding: false FixNamespaceComments: true IndentCaseLabels: false IndentPPDirectives: AfterHash IndentFunctionDeclarationAfterType: false IndentWidth: 4 SortIncludes: false IncludeCategories: - Regex: '[<"](.*\/)?Defines.h[>"]' Priority: 1 - Regex: '<[[:alnum:]_.]+>' Priority: 5 - Regex: '<[[:alnum:]_.\/]+>' Priority: 4 - Regex: '".*"' Priority: 2 IncludeBlocks: Regroup Language: Cpp MaxEmptyLinesToKeep: 2 NamespaceIndentation: None ObjCSpaceAfterProperty: true ObjCSpaceBeforeProtocolList: true PenaltyBreakBeforeFirstCallParameter: 0 PenaltyBreakComment: 1 PenaltyBreakFirstLessLess: 0 PenaltyBreakString: 1 PenaltyExcessCharacter: 10 PenaltyReturnTypeOnItsOwnLine: 1000 PointerAlignment: Left SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInCStyleCastParentheses: false SpacesInContainerLiterals: false SpacesInParentheses: false Standard: Cpp11 ReflowComments: true TabWidth: 4 UseTab: Never
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/tests/config.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * 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. */ #ifndef CUMED_TESTS_CONFIG_H #define CUMED_TESTS_CONFIG_H #include <string> #include <cstdlib> struct AppConfig { std::string test_folder; std::string test_file; std::string temp_folder = "/tmp"; std::string get_input_path(const char* default_value = "private/generic_tiff_000.tif") const { // If `test_file` is absolute path if (!test_folder.empty() && test_file.substr(0, 1) == "/") { return test_file; } else { std::string test_data_folder = test_folder; if (test_data_folder.empty()) { if (const char* env_p = std::getenv("CUCIM_TESTDATA_FOLDER")) { test_data_folder = env_p; } else { test_data_folder = "test_data"; } } if (test_file.empty()) { return test_data_folder + "/" + default_value; } else { return test_data_folder + "/" + test_file; } } } }; extern AppConfig g_config; #endif // CUMED_TESTS_CONFIG_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/tests/test_basic.cpp
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #include "config.h" #include <catch2/catch_test_macros.hpp> #include <chrono> TEST_CASE("Verify file", "[test_basic.cpp]") { REQUIRE(1 == 1); }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/tests/CMakeLists.txt
# # Copyright (c) 2021, NVIDIA CORPORATION. # 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. # include(CTest) enable_testing() ################################################################################ # Add executable: cumed_tests ################################################################################ add_executable(cumed_tests config.h main.cpp test_basic.cpp ) set_target_properties(cumed_tests PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO ) target_compile_features(cumed_tests PRIVATE ${CUCIM_REQUIRED_FEATURES}) # Use generator expression to avoid `nvcc fatal : Value '-std=c++17' is not defined for option 'Werror'` target_compile_options(cumed_tests PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-Werror -Wall -Wextra>) target_compile_definitions(cumed_tests PUBLIC CUMED_VERSION=${PROJECT_VERSION} CUMED_VERSION_MAJOR=${PROJECT_VERSION_MAJOR} CUMED_VERSION_MINOR=${PROJECT_VERSION_MINOR} CUMED_VERSION_PATCH=${PROJECT_VERSION_PATCH} CUMED_VERSION_BUILD=${PROJECT_VERSION_BUILD} ) target_link_libraries(cumed_tests PRIVATE cucim::cucim ${CUCIM_PLUGIN_NAME} deps::catch2 deps::cli11 deps::fmt ) # Add headers in src target_include_directories(cumed_tests PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../src> ) include(Catch) # See https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#catchcmake-and-catchaddtestscmake for other options catch_discover_tests(cumed_tests)
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/tests/main.cpp
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ // #define CATCH_CONFIG_MAIN // #include <catch2/catch_test_macros.hpp> // Implement main explicitly to handle additional parameters. #define CATCH_CONFIG_RUNNER #include "config.h" #include "cucim/core/framework.h" #include <catch2/catch_test_macros.hpp> #include <catch2/catch_session.hpp> #include <string> #include <fmt/format.h> CUCIM_FRAMEWORK_GLOBALS("sample.app") // Global config object AppConfig g_config; /** * Extract `--[option]` or `--[option]=` string from command and set the value to g_config object. * * @param argc number of arguments used for command * @param argv arguments for command * @param obj object reference to modify * @param argument name of argument(option) * @return true if it extracted the value for the option */ static bool extract_test_file_option(int* argc, char** argv, std::string& obj, const char* argument) { std::string arg_str = fmt::format("--{}=", argument); // test_file => --test_file= std::string arg_str2 = fmt::format("--{}", argument); // test_file => --test_file char* value_ptr = nullptr; for (int i = 1; argc && i < *argc; ++i) { if (strncmp(argv[i], arg_str.c_str(), arg_str.size()) == 0) { value_ptr = &argv[i][arg_str.size()]; for (int j = i + 1; argc && j < *argc; ++j) { argv[j - 1] = argv[j]; } --(*argc); argv[*argc] = nullptr; break; } if (strncmp(argv[i], arg_str2.c_str(), arg_str2.size()) == 0 && i + 1 < *argc) { value_ptr = argv[i + 1]; for (int j = i + 2; argc && j < *argc; ++j) { argv[j - 2] = argv[j]; } *argc -= 2; argv[*argc] = nullptr; argv[*argc + 1] = nullptr; break; } } if (value_ptr) { obj = value_ptr; return true; } else { return false; } } int main (int argc, char** argv) { extract_test_file_option(&argc, argv, g_config.test_folder, "test_folder"); extract_test_file_option(&argc, argv, g_config.test_file, "test_file"); extract_test_file_option(&argc, argv, g_config.temp_folder, "temp_folder"); printf("Target test folder: %s (use --test_folder option to change this)\n", g_config.test_folder.c_str()); printf("Target test file : %s (use --test_file option to change this)\n", g_config.test_file.c_str()); printf("Temp folder : %s (use --temp_folder option to change this)\n", g_config.temp_folder.c_str()); int result = Catch::Session().run(argc, argv); return result; }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/benchmarks/config.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * 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. */ #ifndef CUMED_CONFIG_H #define CUMED_CONFIG_H #include <string> struct AppConfig { std::string input_file = "test_data/private/generic_tiff_000.tif"; bool discard_cache = false; int random_seed = 0; bool random_start_location = false; int64_t image_width = 0; int64_t image_height = 0; // Pseudo configurations for google benchmark bool benchmark_list_tests = false; std::string benchmark_filter; // <regex> int benchmark_min_time = 0; // <min_time> int benchmark_repetitions = 0; // <num_repetitions> bool benchmark_report_aggregates_only = false; bool benchmark_display_aggregates_only = false; std::string benchmark_format; // <console|json|csv> std::string benchmark_out; // <filename> std::string benchmark_out_format; // <json|console|csv> std::string benchmark_color; // {auto|true|false} std::string benchmark_counters_tabular; std::string v; // <verbosity> }; #endif // CUMED_CONFIG_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/benchmarks/CMakeLists.txt
# # Copyright (c) 2021, NVIDIA CORPORATION. # 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. # ################################################################################ # Add executable: cumed_benchmarks ################################################################################ add_executable(cumed_benchmarks main.cpp config.h) set_target_properties(cumed_benchmarks PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO ) target_compile_features(cumed_benchmarks PRIVATE ${CUCIM_REQUIRED_FEATURES}) # Use generator expression to avoid `nvcc fatal : Value '-std=c++17' is not defined for option 'Werror'` target_compile_options(cumed_benchmarks PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-Werror -Wall -Wextra>) target_compile_definitions(cumed_benchmarks PUBLIC CUMED_VERSION=${PROJECT_VERSION} CUMED_VERSION_MAJOR=${PROJECT_VERSION_MAJOR} CUMED_VERSION_MINOR=${PROJECT_VERSION_MINOR} CUMED_VERSION_PATCH=${PROJECT_VERSION_PATCH} CUMED_VERSION_BUILD=${PROJECT_VERSION_BUILD} ) target_link_libraries(cumed_benchmarks PRIVATE cucim::cucim deps::googlebenchmark deps::cli11 )
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/benchmarks/main.cpp
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #include "config.h" #include <fcntl.h> #include <unistd.h> #include <cstdlib> #include <cstring> #include <benchmark/benchmark.h> #include <CLI/CLI.hpp> #include <fmt/format.h> #include "cucim/core/framework.h" #include "cucim/io/format/image_format.h" #include "cucim/memory/memory_manager.h" #define XSTR(x) STR(x) #define STR(x) #x //#include <chrono> CUCIM_FRAMEWORK_GLOBALS("cumed.app") static AppConfig g_config; static void test_basic(benchmark::State& state) { for (auto _ : state) { // Implement // auto item = state.range(0); } } BENCHMARK(test_basic)->Unit(benchmark::kMicrosecond)->RangeMultiplier(2)->Range(1, 4096); static bool remove_help_option(int* argc, char** argv) { for (int i = 1; argc && i < *argc; ++i) { if (strncmp(argv[i], "-h", 3) == 0 || strncmp(argv[i], "--help", 7) == 0) { for (int j = i + 1; argc && j < *argc; ++j) { argv[j - 1] = argv[j]; } --(*argc); argv[*argc] = nullptr; return true; } } return false; } static bool setup_configuration() { return true; } // BENCHMARK_MAIN(); int main(int argc, char** argv) { // Skip processing help option bool has_help_option = remove_help_option(&argc, argv); ::benchmark::Initialize(&argc, argv); CLI::App app{ "benchmark: cuMed" }; app.add_option("--test_file", g_config.input_file, "An input file path"); // Pseudo benchmark options app.add_option("--benchmark_list_tests", g_config.benchmark_list_tests, "{true|false}"); app.add_option("--benchmark_filter", g_config.benchmark_filter, "<regex>"); app.add_option("--benchmark_min_time", g_config.benchmark_min_time, "<min_time>"); app.add_option("--benchmark_repetitions", g_config.benchmark_repetitions, "<num_repetitions>"); app.add_option("--benchmark_report_aggregates_only", g_config.benchmark_report_aggregates_only, "{true|false}"); app.add_option("--benchmark_display_aggregates_only", g_config.benchmark_display_aggregates_only, "{true|false}"); app.add_option("--benchmark_format", g_config.benchmark_format, "<console|json|csv>"); app.add_option("--benchmark_out", g_config.benchmark_out, "<filename>"); app.add_option("--benchmark_out_format", g_config.benchmark_out_format, "<json|console|csv>"); app.add_option("--benchmark_color", g_config.benchmark_color, "{auto|true|false}"); app.add_option("--benchmark_counters_tabular", g_config.benchmark_counters_tabular, "{true|false}"); app.add_option("--v", g_config.v, "<verbosity>"); // Append help option if exists if (has_help_option) { argv[argc] = const_cast<char*>("--help"); ++argc; // https://github.com/matepek/vscode-catch2-test-adapter detects google benchmark binaries by the following // text: printf("benchmark [--benchmark_list_tests={true|false}]\n"); } CLI11_PARSE(app, argc, argv); if (!setup_configuration()) { return 1; } ::benchmark::RunSpecifiedBenchmarks(); }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/misc.xml
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" /> <component name="JavaScriptSettings"> <option name="languageLevel" value="ES6" /> </component> </project>
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/.name
cumed
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/cucim.kit.cumed.iml
<?xml version="1.0" encoding="UTF-8"?> <module classpath="CMake" type="CPP_MODULE" version="4" />
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/vcs.xml
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="$PROJECT_DIR$/../../.." vcs="Git" /> </component> </project>
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/codeStyles/codeStyleConfig.xml
<component name="ProjectCodeStyleConfiguration"> <state> <option name="USE_PER_PROJECT_SETTINGS" value="true" /> </state> </component>
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/codeStyles/Project.xml
<component name="ProjectCodeStyleConfiguration"> <code_scheme name="Project" version="173"> <clangFormatSettings> <option name="ENABLED" value="true" /> </clangFormatSettings> </code_scheme> </component>
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates/includes/NVIDIA_CMAKE_HEADER.cmake
# # Copyright (c) $YEAR, NVIDIA CORPORATION. # 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. #
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates/includes/NVIDIA_C_HEADER.h
/* * Copyright (c) $YEAR, NVIDIA CORPORATION. * * 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. */
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates/internal/CMakeLists.txt.cmake
#parse("NVIDIA_CMAKE_HEADER.cmake")
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates/internal/C Header File.h
#parse("NVIDIA_C_HEADER.h") #[[#ifndef]]# ${INCLUDE_GUARD} #[[#define]]# ${INCLUDE_GUARD} #[[#endif]]# //${INCLUDE_GUARD}
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates/internal/C++ Class.cc
#parse("NVIDIA_C_HEADER.h") #[[#include]]# "${HEADER_FILENAME}"
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates/internal/C Source File.c
#parse("NVIDIA_C_HEADER.h") #if (${HEADER_FILENAME}) #[[#include]]# "${HEADER_FILENAME}" #end
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/.idea/fileTemplates/internal/C++ Class Header.h
#parse("NVIDIA_C_HEADER.h") #[[#ifndef]]# ${INCLUDE_GUARD} #[[#define]]# ${INCLUDE_GUARD} ${NAMESPACES_OPEN} class ${NAME} { }; ${NAMESPACES_CLOSE} #[[#endif]]# //${INCLUDE_GUARD}
0