diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44d2d2d803dd55b8bed7723b35ae71998151cec3 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e8ae012a8c69ce4b17d3a8d163c230e10f9a02e Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/bounds.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/bounds.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..671477c594b89c2c6a96ca4f8d1d739609f0320c Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/bounds.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/codecache.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/codecache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19d2552c8d4e4305cbb66a818e00190fd311c194 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/codecache.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fde9bde24e7cf327fedf10dcbbf63c3bbd6993d6 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/coordinate_descent_tuner.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/coordinate_descent_tuner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e183dc55e307790ad6674d123e4d29148dc3222 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/coordinate_descent_tuner.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/cuda_properties.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/cuda_properties.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15048919a02a0c7092be6d5019947738b621c1ed Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/cuda_properties.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b641f635ab9894de07264bbd19c638ac3085b8e8 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/debug.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/debug.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03c3099b74f7829fc7fa79c5c03125185005e72f Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/debug.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/decomposition.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/decomposition.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..369c131c1f4713486b199eeece20d14a9074d2bf Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/decomposition.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/exc.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/exc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61dde697ae99123842f05261e11cf254f5965eed Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/exc.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/freezing.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/freezing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01b2850addca9e53ffa565e1619a40d88d8d0bd9 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/freezing.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85cb72abfcc43ca09e76cd7845950fac9f1bbd38 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/graph.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7340eedfff3d68c9c2be286797c934058eb0eaf Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/graph.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/hooks.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/hooks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a37bc5815a98f0106934281883cf005c99f092ab Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/hooks.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fbcf0503472b32e16acd6c76e473f08f2cb9fbc Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/metrics.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/metrics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63e6d3075f36a7b4d449573bfc1124c4e2062e85 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/metrics.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19c712320df1281c90624375d60cc0aad2d5b879 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..275c0b3b653f71a5ddae278bf247f788d25ac082 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/scheduler.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8ed4509c15b1a8edc222ad70b7fd4f467958f10 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/scheduler.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa1159df568e2acde5f14e23923f3426cf1fad64 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/sizevars.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/sizevars.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce134f894d9576abce643c786c02b69fe8a98350 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/sizevars.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/triton_helpers.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/triton_helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1ef4acd8c2176b05380fb6e5ef2074d526b5206 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/triton_helpers.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/triton_heuristics.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/triton_heuristics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df9225db78cee4adab8ff4b77fc2a67cb89f7c24 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/triton_heuristics.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cd5d86ffdb1bc6d00052712724794e6fc5704bb Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/virtualized.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/virtualized.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c67c8cb808a866195462cb7c1bd93caea1be003 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/virtualized.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..618124dc31764b0ee8ba3615e8d4dbb279cf0bb2 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..624a10e57adc5629539f50d151b5ed553f7bd03c Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/codegen/__pycache__/triton_foreach.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/codegen/__pycache__/triton_foreach.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9d92543679057ab0b502fc1dd29d8f09c132219 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/codegen/__pycache__/triton_foreach.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__init__.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..754ab439025fd9617b69f4ed5fee6c47c2055dc5 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/bmm.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/bmm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52a7a16eefcb920ed844869af3835d3d7b7c9b45 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/bmm.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/conv.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/conv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef18e76dceb7a1c1f7d2b66d488d59aa959c1617 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/conv.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c2e1b0a143ef39122c758446503519e296873a3 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm_common.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..336016d6749cfadda6820cfebf528e80c357ea3c Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm_common.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm_plus_mm.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm_plus_mm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7e9df3aed467bff52957b7a4baa4fe5cc17712b Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/mm_plus_mm.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/unpack_mixed_mm.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/unpack_mixed_mm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4729913f66e8aeac4ce9a984e1d7013925cedde1 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/__pycache__/unpack_mixed_mm.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/bmm.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/bmm.py new file mode 100644 index 0000000000000000000000000000000000000000..9b414b2480002e3c198926c3c9823311f3fbe3e2 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/bmm.py @@ -0,0 +1,128 @@ +import torch + +from ..lowering import register_lowering +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + TritonTemplate, +) +from ..utils import ceildiv as cdiv, use_aten_gemm_kernels, use_triton_template + +from .mm_common import addmm_epilogue, mm_args, mm_configs, mm_options + +aten = torch.ops.aten + + +def bmm_grid(b, m, n, meta): + return (cdiv(m, meta["BLOCK_M"]) * cdiv(n, meta["BLOCK_N"]), b, 1) + + +bmm_template = TritonTemplate( + name="bmm", + grid=bmm_grid, + source=r""" +{{def_kernel("A", "B")}} + M = {{size("A", -2)}} + N = {{size("B", -1)}} + K = {{size("A", -1)}} + + stride_aq = {{stride("A", 0)}} + stride_am = {{stride("A", 1)}} + stride_ak = {{stride("A", 2)}} + + stride_bq = {{stride("B", 0)}} + stride_bk = {{stride("B", 1)}} + stride_bn = {{stride("B", 2)}} + + # based on triton.ops.matmul + pid = tl.program_id(0) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + + idx_q = tl.program_id(1) # batch dimension for BMM + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak + idx_q*stride_aq) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn + idx_q*stride_bq) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.) + b = tl.load(B, mask=rk[:, None] < k, other=0.) + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + A += BLOCK_K * stride_ak + B += BLOCK_K * stride_bk + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + idx_q = tl.program_id(1) # batch dimension for BMM + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_q", "idx_m", "idx_n"), "acc", "mask")}} +""", +) + +aten_bmm = ExternKernelChoice(torch.bmm, "at::bmm_out") +aten_baddbmm = ExternKernelChoice(torch.baddbmm, "at::baddbmm_out") + + +@register_lowering(aten.bmm) +def tuned_bmm(mat1, mat2, *, layout=None): + m, n, k, layout, mat1, mat2 = mm_args(mat1, mat2, layout=layout) + + # options to tune from + choices = [aten_bmm.bind((mat1, mat2), layout)] if use_aten_gemm_kernels() else [] + if use_triton_template(layout): + for config in mm_configs(m, n, k): + bmm_template.maybe_append_choice( + choices, + (mat1, mat2), + layout, + **mm_options(config, k, layout), + ) + + return autotune_select_algorithm("bmm", choices, [mat1, mat2], layout) + + +# Don't register this since it is slower than decomposing it +# @register_lowering(aten.baddbmm) +def tuned_baddbmm(inp, mat1, mat2, *, alpha=1, beta=1, layout=None): + m, n, k, layout, mat1, mat2, inp = mm_args(mat1, mat2, inp, layout=layout) + + # options to tune from + choices = ( + [aten_baddbmm.bind((inp, mat1, mat2), layout, alpha=alpha, beta=beta)] + if use_aten_gemm_kernels() + else [] + ) + if use_triton_template(layout): + for config in mm_configs(m, n, k): + bmm_template.maybe_append_choice( + choices, + (inp, mat1, mat2), + layout, + **mm_options(config, k, layout), + prefix_args=1, + epilogue_fn=addmm_epilogue(layout.dtype, alpha, beta), + ) + + return autotune_select_algorithm("baddbmm", choices, [inp, mat1, mat2], layout) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/conv.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d412445b9b4cd8bb3cdc4f16ef087737e42e05 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/conv.py @@ -0,0 +1,487 @@ +from __future__ import annotations + +import functools +import logging +from typing import cast, List, Tuple, TypedDict + +import torch +from .. import config, ir +from ..ir import TensorBox + +from ..lowering import ( + add_layout_constraint, + constrain_to_fx_strides, + lowerings as L, + register_lowering, +) +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + TritonTemplate, +) +from ..utils import ( + ceildiv, + is_ones, + is_zeros, + pad_listlike, + sympy_product, + use_triton_template, +) +from ..virtualized import V +from .mm_common import filtered_configs + +log = logging.getLogger(__name__) + + +aten = torch.ops.aten + + +def conv_grid(n, c, h, w, meta): + return ( + ceildiv(n * h * w, meta["BLOCK_M"]), + ceildiv(c, meta["BLOCK_N"]), + meta["GROUPS"], + ) + + +# List of dictionaries to store the kernel configs. Configs that evaluate to true +# will be utilised on the target platform +kernel_configs = [ + # "BLOCK_M", "BLOCK_N", "BLOCK_K", "num_stages", "num_warps" + {"config": (64, 256, 16, 2, 4), "cond": True}, + {"config": (256, 64, 16, 2, 4), "cond": True}, + {"config": (1024, 16, 16, 1, 8), "cond": True}, + {"config": (128, 128, 32, 2, 8), "cond": True}, + {"config": (64, 64, 32, 2, 4), "cond": True}, + {"config": (64, 256, 32, 2, 8), "cond": True}, + {"config": (256, 64, 32, 2, 8), "cond": True}, +] + +# Create filtered list of configs based on conv +platform_configs = tuple( + cast(Tuple[int, int, int, int, int], config["config"]) + for config in kernel_configs + if config["cond"] +) + +# On ROCm convert num_stages to 1 as pipelining provides no benefit +if torch.version.hip: + platform_configs = tuple( + (config[0], config[1], config[2], 1, config[4]) for config in platform_configs + ) + +conv_configs = functools.partial( + filtered_configs, + configs=platform_configs, +) + +LOOP_BODY = """ + idx_x_h = i - PADDING_H + idx_y_h * STRIDE_H + idx_x_w = j - PADDING_W + idx_y_w * STRIDE_W + idx_x_c = tl.arange(0, BLOCK_K) + k + + x_ptrs = x_base + ( + (idx_x_h * stride_xh)[:, None] + + (idx_x_w * stride_xw)[:, None] + + (idx_x_c * stride_xc)[None, :] + ) + mask_x = ( + (idx_n < BATCH)[:, None] + & (idx_x_h >= 0)[:, None] + & (idx_x_h < IN_H)[:, None] + & (idx_x_w >= 0)[:, None] + & (idx_x_w < IN_W)[:, None] + & (idx_x_c < GROUP_IN_C)[None, :] + ) + matrix_x = tl.load(x_ptrs, mask=mask_x, other=0.0) + + w_ptrs = w_base + ( + (idx_x_c * stride_wc_in)[:, None] + (i * stride_wh) + (j * stride_ww) + ) + mask_w = (idx_x_c[:, None] < GROUP_IN_C) & (idx_y_c[None, :] < GROUP_OUT_C) + matrix_w = tl.load(w_ptrs, mask=mask_w, other=0.0) + acc += tl.dot(matrix_x, matrix_w, allow_tf32=ALLOW_TF32) +""" + +""" +This is a relatively simple conv implementation that can likely be +improved. Many alternate conv versions can be found here: +https://github.com/pytorch/torchdynamo/pull/971 +""" +conv2d_template = TritonTemplate( + name="convolution", + grid=conv_grid, + source=r""" +{{def_kernel("X", "W")}} + # Tensor dimensions + BATCH = {{size("X", 0)}} + IN_C = {{size("X", 1)}} + IN_H = {{size("X", 2)}} + IN_W = {{size("X", 3)}} + OUT_C = {{size(None, 1)}} + OUT_H = {{size(None, 2)}} + OUT_W = {{size(None, 3)}} + + # Strides: + stride_xn = {{stride("X", 0)}} + stride_xc = {{stride("X", 1)}} + stride_xh = {{stride("X", 2)}} + stride_xw = {{stride("X", 3)}} + stride_wc_out = {{stride("W", 0)}} + stride_wc_in = {{stride("W", 1)}} + stride_wh = {{stride("W", 2)}} + stride_ww = {{stride("W", 3)}} + + nhw = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) + idx_y_w = nhw % OUT_W + nh = nhw // OUT_W + idx_y_h = nh % OUT_H + idx_n = nh // OUT_H + idx_y_c = tl.program_id(1) * BLOCK_N + tl.arange(0, BLOCK_N) + +{% if GROUPS == 1 %} + group = 0 + GROUP_IN_C = IN_C + GROUP_OUT_C = OUT_C +{% else %} + group = tl.program_id(2) + GROUP_IN_C = IN_C // GROUPS + GROUP_OUT_C = OUT_C // GROUPS +{% endif %} + + x_base = X + (group * stride_xc * GROUP_IN_C + idx_n * stride_xn)[:, None] + w_base = ( + W + (group * stride_wc_out * GROUP_OUT_C + idx_y_c * stride_wc_out)[None, :] + ) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + +{% if UNROLL %} +{% for i in range(KERNEL_H) %} +{% for j in range(KERNEL_W) %} + i = {{i}} + j = {{j}} + for k in range(0, GROUP_IN_C, BLOCK_K): + """ + + LOOP_BODY + + """ +{% endfor %} +{% endfor %} +{% else %} + # Could be simplified, but slightly slower: + # for i in range(KERNEL_H): + # for j in range(KERNEL_W): + # for k in range(0, GROUP_IN_C, BLOCK_K): + BLOCK_K_COUNT = (GROUP_IN_C + BLOCK_K - 1) // BLOCK_K + for ijk in range(KERNEL_H * KERNEL_W * BLOCK_K_COUNT): + k = (ijk % BLOCK_K_COUNT) * BLOCK_K + ij = ijk // BLOCK_K_COUNT + i = ij // KERNEL_W + j = ij % KERNEL_W + """ + + LOOP_BODY + + """ +{% endif %} + + mask = ( + (idx_n < BATCH)[:, None] + & (idx_y_h < OUT_H)[:, None] + & (idx_y_w < OUT_W)[:, None] + & (idx_y_c < GROUP_OUT_C)[None, :] + ) + idx_n = idx_n[:, None] + idx_c = idx_y_c[None, :] + group * GROUP_OUT_C + idx_h = idx_y_h[:, None] + idx_w = idx_y_w[:, None] + + # inductor generates a suffix + {{store_output(("idx_n", "idx_c", "idx_h", "idx_w"), "acc", "mask")}} +""", +) + +aten_convolution = ExternKernelChoice( + torch.convolution, + "at::convolution", + has_out_variant=False, +) + + +def conv1x1_via_mm(x, w, *, out): + w = torch.squeeze(torch.squeeze(w, -1), -1) + return torch.matmul( + x.permute(0, 2, 3, 1), w.permute(1, 0), out=out.permute(0, 2, 3, 1) + ) + + +aten_conv1x1_via_mm = ExternKernelChoice(conv1x1_via_mm, None) + + +class ConvLayoutParams(TypedDict): + stride: tuple[int, ...] + padding: tuple[int, ...] + dilation: tuple[int, ...] + transposed: bool + output_padding: tuple[int, ...] + groups: int + + +def conv_layout( + x: TensorBox, + weight: TensorBox, + bias: TensorBox, + stride: tuple[int, ...], + padding: tuple[int, ...], + dilation: tuple[int, ...], + transposed: bool, + output_padding: tuple[int, ...], + groups: int, +) -> ir.Layout: + """Determine output layout for a convolution""" + with V.graph.fake_mode: + output = torch.ops.aten.convolution( + ir.ir_node_to_tensor(x, guard_shape=True), + ir.ir_node_to_tensor(weight, guard_shape=True), + ir.ir_node_to_tensor(bias, guard_shape=True), + stride, + tuple(V.graph.sizevars.size_hint(p) for p in padding), + dilation, + transposed, + tuple(V.graph.sizevars.size_hint(p) for p in output_padding), + groups, + ) + sizes = ir.convert_shape_to_inductor(output.size()) + stride = ir.convert_shape_to_inductor(output.stride()) + + return ir.FixedLayout( + x.get_device(), + x.get_dtype(), + sizes, + stride, + ) + + +def channels_last_order(rank): + order = list(reversed(range(rank))) + order.insert(1, order.pop(-1)) + return order + + +def convert_1x1_conv_to_mm(x, weight, bias): + # special case for 1x1 convolution, which is actually just a matmul + rank = len(weight.get_size()) + for _ in range(rank - 2): + weight = L[aten.squeeze](weight, dim=-1) + weight = L[aten.permute](weight, [1, 0]) + + if x.get_size()[0] != 1: + x = ir.ExternKernel.require_stride_order(x, channels_last_order(rank)) + else: + x.realize() + x.freeze_layout() + + x_permute = list(range(rank)) + x_permute.append(x_permute.pop(1)) + x = L[aten.permute](x, x_permute) + *sizes, in_chan = x.get_size() + x = L[aten.reshape](x, [sympy_product(sizes), in_chan]) + if bias is None: + result = L[aten.mm](x, weight) + else: + result = L[aten.addmm](bias, x, weight) + result = L[aten.reshape](result, [*sizes, -1]) + result_permute = list(range(rank)) + result_permute.insert(1, result_permute.pop(-1)) + return L[aten.permute](result, result_permute) + + +@register_lowering(aten.convolution) +def convolution( + x: TensorBox, + weight: TensorBox, + bias: TensorBox, + stride: List[int], + padding: List[int], + dilation: List[int], + transposed: bool, + output_padding: List[int], + groups: int, +): + stride = tuple(stride) + padding = tuple(padding) + dilation = tuple(dilation) + output_padding = tuple(output_padding) + assert isinstance(groups, int) + kwargs: ConvLayoutParams = { + "stride": stride, + "padding": padding, + "dilation": dilation, + "transposed": transposed, + "output_padding": output_padding, + "groups": groups, + } + + if len(x.get_size()) == len(weight.get_size()) - 1: + # add batch dimension to simplify rest of function + return L[aten.squeeze]( + convolution(L[aten.expand](x, [1, *x.get_size()]), weight, bias, **kwargs), + dim=0, + ) + + out_chan, in_chan, *kernel_shape = V.graph.sizevars.evaluate_static_shapes( + weight.get_size() + ) + ndim = len(kernel_shape) + stride = pad_listlike(stride, ndim) + padding = pad_listlike(padding, ndim) + dilation = pad_listlike(dilation, ndim) + output_padding = pad_listlike(output_padding, ndim) + + def channels_last_conv(): + if V.graph.layout_opt and ndim == 2: + return True + + layout = conv_layout(x, weight, None, **kwargs) + req_stride_order = ir.get_stride_order( + V.graph.sizevars.size_hints(layout.stride) + ) + return req_stride_order == ir.NHWC_STRIDE_ORDER + + autotuning_gemm = config.max_autotune or config.max_autotune_gemm + + if ( + (config.conv_1x1_as_mm or (autotuning_gemm and channels_last_conv())) + and is_ones(kernel_shape) + and is_ones(stride) + and is_zeros(padding) + and is_ones(dilation) + and not transposed + and is_zeros(output_padding) + and groups == 1 + ): + return convert_1x1_conv_to_mm(x, weight, bias) + + if bias is not None and ir.get_device_type(x) != "cpu": + # peel off the bias, cudnn is slower with it + result = convolution(x, weight, None, **kwargs) + return L[aten.add]( + result, L[aten.view](bias, [result.get_size()[1]] + ndim * [1]) + ) + + x.realize() + weight.realize() + + # ndim can be 1 for convolution in models such as demucs + # TODO: check if it's beneficial to convert Conv1d to Conv2d and then + # apply channels last. + if V.graph.layout_opt and ndim == 2: + V.graph.num_channels_last_conv += 1 + x = ir.ExternKernel.require_channels_last(x) + # TODO maybe we can convert weights to channels last just once before + # running the model. + weight = ir.ExternKernel.require_channels_last(weight) + layout = conv_layout(x, weight, None, **kwargs) + else: + layout = conv_layout(x, weight, None, **kwargs) + req_stride_order = ir.get_stride_order( + V.graph.sizevars.size_hints(layout.stride) + ) + x = ir.ExternKernel.require_stride_order(x, req_stride_order) + weight = ir.ExternKernel.require_stride_order(weight, req_stride_order) + + ordered_kwargs_for_cpp_kernel = [ + "stride", + "padding", + "dilation", + "transposed", + "output_padding", + "groups", + ] + if bias is None: + args = [x, weight] + kwargs["bias"] = None # type: ignore[typeddict-unknown-key] + ordered_kwargs_for_cpp_kernel.insert(0, "bias") + else: + args = [x, weight, bias] + bias.realize() + bias.freeze_layout() + V.graph.sizevars.evaluate_static_shapes(bias.get_size()) + + choices = [ + aten_convolution.bind(args, layout, ordered_kwargs_for_cpp_kernel, **kwargs) + ] + if ( + use_triton_template(layout) + # templates only support these: + and ndim == 2 + and is_ones(dilation) + and not transposed + and is_zeros(output_padding) + # there are some odd models where this check fails (e.g. shufflenet_v2_x1_0) + and V.graph.sizevars.statically_known_equals(in_chan, x.get_size()[1]) + ): + if ( + is_ones(kernel_shape) + and is_ones(stride) + and is_zeros(padding) + and groups == 1 + ): + choices.append(aten_conv1x1_via_mm.bind(args, layout)) + + for cfg in conv_configs( + sympy_product([x.get_size()[0], *x.get_size()[2:]]), + out_chan, + in_chan, + ): + conv2d_template.maybe_append_choice( + choices, + (x, weight), + layout, + KERNEL_H=kernel_shape[0], + KERNEL_W=kernel_shape[1], + STRIDE_H=stride[0], + STRIDE_W=stride[1], + PADDING_H=padding[0], + PADDING_W=padding[1], + GROUPS=groups, + # TODO(jansel): try unroll for bigger kernels once fixed: + # https://github.com/openai/triton/issues/1254 + UNROLL=is_ones(kernel_shape), + ALLOW_TF32=torch.backends.cudnn.allow_tf32, + num_stages=cfg.num_stages, + num_warps=cfg.num_warps, + **cfg.kwargs, + ) + + return autotune_select_algorithm("convolution", choices, args, layout) + + +@register_lowering(aten._convolution) +def _convolution( + x, + weight, + bias, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + benchmark, + deterministic, + cudnn_enabled, + allow_tf32, +): + return convolution( + x, weight, bias, stride, padding, dilation, transposed, output_padding, groups + ) + + +def constrain_conv_to_fx_strides(fx_node, *args, **kwargs): + assert fx_node.target == torch.ops.aten.convolution.default + if V.graph.layout_opt: + return args, kwargs + else: + return constrain_to_fx_strides(fx_node, *args, **kwargs) + + +add_layout_constraint(aten.convolution, constrain_conv_to_fx_strides) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm.py new file mode 100644 index 0000000000000000000000000000000000000000..576c195382d8750b7b0cb57a42ec614f334a23ac --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm.py @@ -0,0 +1,238 @@ +import logging + +import torch + +from .. import config as inductor_config +from ..lowering import register_lowering +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + TritonTemplate, +) +from ..utils import use_aten_gemm_kernels, use_triton_template +from .mm_common import ( + addmm_epilogue, + int8_mm_configs, + mm_args, + mm_configs, + mm_grid, + mm_options, +) + +log = logging.getLogger(__name__) +aten = torch.ops.aten + +mm_template = TritonTemplate( + name="mm", + grid=mm_grid, + source=r""" +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.) + b = tl.load(B, mask=rk[:, None] < k, other=0.) + if B_PROLOGUE_CAST_TYPE is not None: + b = b.to(B_PROLOGUE_CAST_TYPE) + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + A += BLOCK_K * stride_ak + B += BLOCK_K * stride_bk + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask")}} +""", +) + +aten_mm = ExternKernelChoice(torch.mm, "at::mm_out") + + +aten_addmm = ExternKernelChoice(torch.addmm, "at::addmm_out") + +aten__int_mm = ExternKernelChoice(torch._int_mm, "at::_int_mm") + + +def _is_int8_mat(mat): + return mat.get_dtype() in (torch.int8, torch.uint8) + + +def bias_addmm(inp, mat1, mat2, *, out=None, alpha=1, beta=1): + """ + Giving torch.addmm a 1D tensor calls a different (faster) cublasLt + kernel under the hood. There are a few shapes where this is slower, + but they are rare. + """ + if inp.stride(0) == 0 or inp.size(0) == 1: + return torch.addmm(inp[0], mat1, mat2, out=out, alpha=alpha, beta=beta) + return torch.addmm(inp, mat1, mat2, out=out, alpha=alpha, beta=beta) + + +aten_bias_addmm = ExternKernelChoice(bias_addmm, None) + + +@register_lowering(aten.mm) +def tuned_mm(mat1, mat2, *, layout=None): + m, n, k, layout, mat1, mat2 = mm_args(mat1, mat2, layout=layout) + + # options to tune from + choices = [aten_mm.bind((mat1, mat2), layout)] if use_aten_gemm_kernels() else [] + if m * n != 0 and use_triton_template(layout): + for config in mm_configs(m, n, k): + mm_template.maybe_append_choice( + choices, + (mat1, mat2), + layout, + **mm_options(config, k, layout), + ) + + return autotune_select_algorithm("mm", choices, [mat1, mat2], layout) + + +@register_lowering(aten._int_mm) +def tuned_int_mm(mat1, mat2, *, layout=None): + m, n, k, layout, mat1, mat2 = mm_args( + mat1, mat2, layout=layout, out_dtype=torch.int32 + ) + choices = ( + [aten__int_mm.bind((mat1, mat2), layout)] if use_aten_gemm_kernels() else [] + ) + if m * n != 0 and use_triton_template(layout, enable_int32=True): + # TODO: Re-enable eager mode implementation once cuBLAS is fixed + choices = [] + for config in int8_mm_configs(m, n, k): + mm_template.maybe_append_choice( + choices, + (mat1, mat2), + layout, + **mm_options(config, k, layout), + ) + return autotune_select_algorithm("int_mm", choices, [mat1, mat2], layout) + + +@register_lowering(aten.addmm) +def tuned_addmm(inp, mat1, mat2, *, alpha=1, beta=1, layout=None): + ordered_kwargs_for_cpp_kernel = ("beta", "alpha") + + m, n, k, layout, mat1, mat2, inp_expanded = mm_args(mat1, mat2, inp, layout=layout) + if m * n == 0 or not use_triton_template(layout): + choices = ( + [ + aten_addmm.bind( + (inp, mat1, mat2), + layout, + ordered_kwargs_for_cpp_kernel, + alpha=alpha, + beta=beta, + ) + ] + if use_aten_gemm_kernels() + else [] + ) + return autotune_select_algorithm("addmm", choices, [inp, mat1, mat2], layout) + + choices = ( + [ + aten_addmm.bind( + (inp_expanded, mat1, mat2), + layout, + ordered_kwargs_for_cpp_kernel, + alpha=alpha, + beta=beta, + ) + ] + if use_aten_gemm_kernels() + else [] + ) + if ( + inp_expanded.get_stride()[0] == 0 + and inp_expanded.get_device().type == "cuda" + and inductor_config.triton.autotune_cublasLt + ): + # unexpand inp to make sure fused addmm from cublasLt is used + choices.insert( + 0, + aten_bias_addmm.bind( + (inp_expanded, mat1, mat2), layout, alpha=alpha, beta=beta + ), + ) + + for config in mm_configs(m, n, k): + mm_template.maybe_append_choice( + choices, + (inp_expanded, mat1, mat2), + layout, + **mm_options(config, k, layout), + prefix_args=1, + epilogue_fn=addmm_epilogue(layout.dtype, alpha, beta), + ) + + return autotune_select_algorithm( + "addmm", choices, [inp_expanded, mat1, mat2], layout + ) + + +def fallback_mixed_mm(mat1, mat2, *, out): + return torch.mm(mat1, mat2.to(mat1.dtype), out=out) + + +aten_fallback_mixed_mm = ExternKernelChoice(fallback_mixed_mm, None) + + +def tuned_mixed_mm(mat1, mat2, mat2_dtype): + m, n, k, layout, mat1, mat2 = mm_args(mat1, mat2, layout=None) + choices = [aten_fallback_mixed_mm.bind((mat1, mat2), layout)] + if mat1.layout.dtype != torch.float32 and not mat2.layout.is_contiguous(): + # can't use triton kernel unless one of these is true + return autotune_select_algorithm("mixed_mm", choices, [mat1, mat2], layout) + if inductor_config.force_mixed_mm: + choices = [] + b_prologue_cast_type = f"tl.{mat2_dtype}".replace("torch.", "") + has_int8_tensor = _is_int8_mat(mat1) or _is_int8_mat(mat2) + for config in mm_configs(m, n, k, has_int8_tensor=has_int8_tensor): + mm_template.maybe_append_choice( + choices, + (mat1, mat2), + layout, + **mm_options(config, k, layout, b_prologue_cast_type), + ) + return autotune_select_algorithm("mixed_mm", choices, [mat1, mat2], layout) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm_common.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm_common.py new file mode 100644 index 0000000000000000000000000000000000000000..60f7123eef18eb62b2109391cdbc20afee2535fa --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm_common.py @@ -0,0 +1,200 @@ +import functools +import logging +from typing import cast, List, Tuple + +import sympy + +import torch +from torch._inductor.select_algorithm import realize_inputs +from torch._inductor.virtualized import V +from ..utils import ceildiv as cdiv, next_power_of_2 + +log = logging.getLogger(__name__) + + +def triton_config(num_stages, num_warps, **kwargs): + from triton import Config + + return Config(kwargs, num_stages=num_stages, num_warps=num_warps) + + +def filtered_configs( + m: int, + n: int, + k: int, + configs: List[Tuple[int, int, int, int, int]], + has_int8_tensor=False, +): + """Heuristic to shrink configs when they are bigger than the input size""" + + # According to https://github.com/openai/triton/issues/2156#issuecomment-1695897424 + # it's safer to use at least [32, 32] block size for int8/uint8 + # tensors + min_block_size = 32 if has_int8_tensor else 16 + m = max(next_power_of_2(V.graph.sizevars.size_hint(m)), min_block_size) + n = max(next_power_of_2(V.graph.sizevars.size_hint(n)), min_block_size) + k = max(next_power_of_2(V.graph.sizevars.size_hint(k)), min_block_size) + used = set() + for block_m, block_n, block_k, num_stages, num_warps in configs: + # shrink configs for small sizes + block_m = max(min(block_m, m), min_block_size) + block_n = max(min(block_n, n), min_block_size) + block_k = max(min(block_k, k), min_block_size) + # each warp computes 16x16 tile = 256 + num_warps = min(num_warps, block_m * block_n // 256) + if (block_m, block_n, block_k, num_stages, num_warps) not in used: + used.add((block_m, block_n, block_k, num_stages, num_warps)) + yield triton_config( + BLOCK_M=block_m, + BLOCK_N=block_n, + BLOCK_K=block_k, + num_stages=num_stages, + num_warps=num_warps, + ) + + +# List of dictionaries to store the kernel configs. Configs that evaluate to true +# will be utilised on the target platform +mm_kernel_configs = [ + # "BLOCK_M", "BLOCK_N", "BLOCK_K", "num_stages", "num_warps" + {"config": (64, 64, 32, 2, 4), "cond": True}, + {"config": (64, 128, 32, 3, 4), "cond": True}, + {"config": (128, 64, 32, 3, 4), "cond": True}, + {"config": (64, 128, 32, 4, 8), "cond": True}, + {"config": (128, 64, 32, 4, 8), "cond": True}, + {"config": (64, 32, 32, 5, 8), "cond": True}, + {"config": (32, 64, 32, 5, 8), "cond": True}, + {"config": (128, 128, 32, 2, 8), "cond": True}, + {"config": (64, 64, 64, 3, 8), "cond": True}, + {"config": (32, 32, 128, 2, 4), "cond": torch.version.hip is None}, + {"config": (64, 64, 16, 2, 4), "cond": True}, + {"config": (32, 32, 16, 1, 2), "cond": True}, +] + +int8_mm_kernel_configs = [ + {"config": (64, 64, 32, 2, 4), "cond": True}, + {"config": (64, 128, 32, 3, 4), "cond": True}, + {"config": (128, 64, 32, 3, 4), "cond": True}, + {"config": (64, 128, 32, 4, 8), "cond": True}, + {"config": (128, 64, 32, 4, 8), "cond": True}, + {"config": (64, 32, 32, 5, 8), "cond": True}, + {"config": (32, 64, 32, 5, 8), "cond": True}, + {"config": (128, 128, 32, 2, 8), "cond": True}, + {"config": (64, 64, 64, 3, 8), "cond": True}, + # {"config": (32, 32, 128, 2, 4), "cond": True}, + # {"config": (64, 64, 16, 2, 4), "cond": True}, + # {"config": (32, 32, 16, 1, 2), "cond": True}, + {"config": (128, 256, 128, 3, 8), "cond": torch.version.hip is None}, + {"config": (256, 128, 128, 3, 8), "cond": torch.version.hip is None}, +] + +# Create filtered list of configs based on cond evaluation + + +mm_platform_configs = tuple( + cast(Tuple[int, int, int, int, int], config["config"]) + for config in mm_kernel_configs + if config["cond"] +) +int8_platform_configs = tuple( + cast(Tuple[int, int, int, int, int], config["config"]) + for config in int8_mm_kernel_configs + if config["cond"] +) + +# On ROCm convert num_stages to 1 as pipelining provides no benefit +if torch.version.hip: + mm_platform_configs = tuple( + (config[0], config[1], config[2], 1, config[4]) + for config in mm_platform_configs + ) + int8_platform_configs = tuple( + (config[0], config[1], config[2], 1, config[4]) + for config in mm_platform_configs + ) + +mm_configs = functools.partial( + filtered_configs, + configs=mm_platform_configs, +) + +int8_mm_configs = functools.partial( + filtered_configs, + configs=int8_platform_configs, +) + + +def mm_grid(m, n, meta): + """ + The CUDA grid size for matmul triton templates. + """ + return (cdiv(m, meta["BLOCK_M"]) * cdiv(n, meta["BLOCK_N"]), 1, 1) + + +def acc_type(dtype): + if dtype in (torch.float16, torch.bfloat16): + return "tl.float32" + return f"tl.{dtype}".replace("torch.", "") + + +def mm_options(config, sym_k, layout, b_prologue_cast_type=None): + """ + Common options to matmul triton templates. + """ + even_k_symbolic = ( + # it isn't worth guarding on this + sympy.gcd(sym_k, config.kwargs["BLOCK_K"]) + == config.kwargs["BLOCK_K"] + ) + return dict( + GROUP_M=8, + EVEN_K=even_k_symbolic, + ALLOW_TF32=torch.backends.cuda.matmul.allow_tf32, + ACC_TYPE=acc_type(layout.dtype), + B_PROLOGUE_CAST_TYPE=b_prologue_cast_type, + num_stages=config.num_stages, + num_warps=config.num_warps, + **config.kwargs, + ) + + +def mm_args(mat1, mat2, *others, layout=None, out_dtype=None, use_4x2_dim=False): + """ + Common arg processing for mm,bmm,addmm,etc + """ + mat1, mat2 = realize_inputs(mat1, mat2) + *b1, m, k1 = mat1.get_size() + *b2, k2, n = mat2.get_size() + b = [V.graph.sizevars.guard_equals(a, b) for a, b in zip(b1, b2)] + if use_4x2_dim: + k2 = k2 * 2 + k = V.graph.sizevars.guard_equals(k1, k2) + if layout is None: + from torch._inductor.ir import FixedLayout + + if out_dtype is None: + out_dtype = mat1.get_dtype() + layout = FixedLayout( + mat1.get_device(), + out_dtype, + [*b, m, n], + ) + else: + assert out_dtype is None, "out_dtype is ignored if layout is specified." + + from ..lowering import expand + + others = [realize_inputs(expand(x, layout.size)) for x in others] + + return [m, n, k, layout, mat1, mat2, *others] + + +def addmm_epilogue(dtype, alpha, beta): + def epilogue(acc, bias): + if alpha != 1: + acc = V.ops.mul(acc, V.ops.constant(alpha, dtype)) # type: ignore[attr-defined] + if beta != 1: + bias = V.ops.mul(bias, V.ops.constant(beta, dtype)) # type: ignore[attr-defined] + return V.ops.add(acc, bias) # type: ignore[attr-defined] + + return epilogue diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm_plus_mm.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm_plus_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..40564b3627e0e83b966eb383ca13015d7ebb53ab --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/mm_plus_mm.py @@ -0,0 +1,239 @@ +import functools + +import torch + +from ..lowering import lowerings +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + TritonTemplate, +) +from ..utils import use_aten_gemm_kernels, use_triton_template +from ..virtualized import V +from .mm_common import mm_args, mm_grid, mm_options + +aten = torch.ops.aten + +aten_mm_plus_mm = ExternKernelChoice( + torch.ops.inductor._mm_plus_mm, "torch::inductor::_mm_plus_mm" +) + +mm_plus_mm_template = TritonTemplate( + name="mm_plus_mm", + grid=mm_grid, + debug=False, + source=r""" +{{def_kernel("A", "B", "C", "D")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K1 = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + # K2 = {{size("C", 1)}} + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + stride_cm = {{stride("C", 0)}} + stride_ck = {{stride("C", 1)}} + stride_dk = {{stride("D", 0)}} + stride_dn = {{stride("D", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + C = C + (ram[:, None] * stride_cm + rk[None, :] * stride_ck) + D = D + (rk[:, None] * stride_dk + rbn[None, :] * stride_dn) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + for k1 in range(K1, 0, -BLOCK_K): + # First matmul with A @ B + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k1, other=0.) + b = tl.load(B, mask=rk[:, None] < k1, other=0.) + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + A += BLOCK_K * stride_ak + B += BLOCK_K * stride_bk + + for k2 in range(K1, 0, -BLOCK_K): + + # Second matmul with C @ D + if EVEN_K: + c = tl.load(C) + d = tl.load(D) + else: + c = tl.load(C, mask=rk[None, :] < k2, other=0.) + d = tl.load(D, mask=rk[:, None] < k2, other=0.) + acc += tl.dot(c, d, allow_tf32=ALLOW_TF32) + C += BLOCK_K * stride_ck + D += BLOCK_K * stride_dk + + + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask")}} +""", +) + + +@functools.lru_cache(None) +def mm_configs(): + import triton + + # List of dictionaries to store the kernel configs. Configs that evaluate to true + # will be utilised on the target platform + mm_triton_configs = [ + { + "config": {"BLOCK_M": 64, "BLOCK_N": 64, "BLOCK_K": 32}, + "num_stages": 2, + "num_warps": 4, + "cond": True, + }, + { + "config": {"BLOCK_M": 64, "BLOCK_N": 64, "BLOCK_K": 32}, + "num_stages": 3, + "num_warps": 8, + "cond": True, + }, + { + "config": {"BLOCK_M": 64, "BLOCK_N": 64, "BLOCK_K": 32}, + "num_stages": 4, + "num_warps": 16, + "cond": True, + }, + { + "config": {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32}, + "num_stages": 4, + "num_warps": 8, + "cond": True, + }, + { + "config": {"BLOCK_M": 32, "BLOCK_N": 64, "BLOCK_K": 32}, + "num_stages": 4, + "num_warps": 8, + "cond": True, + }, + { + "config": {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32}, + "num_stages": 1, + "num_warps": 8, + "cond": True, + }, + { + "config": {"BLOCK_M": 64, "BLOCK_N": 64, "BLOCK_K": 64}, + "num_stages": 1, + "num_warps": 8, + "cond": True, + }, + { + "config": {"BLOCK_M": 32, "BLOCK_N": 32, "BLOCK_K": 128}, + "num_stages": 1, + "num_warps": 8, + "cond": torch.version.hip is None, + }, + { + "config": {"BLOCK_M": 64, "BLOCK_N": 64, "BLOCK_K": 16}, + "num_stages": 2, + "num_warps": 4, + "cond": True, + }, + { + "config": {"BLOCK_M": 32, "BLOCK_N": 32, "BLOCK_K": 16}, + "num_stages": 1, + "num_warps": 2, + "cond": True, + }, + ] + + # Filter out configs in which cond evaluates to true + # On ROCm convert num_stages to 1 as pipelining provides no benefit + if torch.version.hip: + filtered_configs = [ + triton.Config(c["config"], num_stages=1, num_warps=c["num_warps"]) + for c in mm_triton_configs + if c["cond"] + ] + else: + filtered_configs = [ + triton.Config( + c["config"], num_stages=c["num_stages"], num_warps=c["num_warps"] + ) + for c in mm_triton_configs + if c["cond"] + ] + + return filtered_configs + + +def tuned_mm_plus_mm(mat1, mat2, mat3, mat4, *, layout=None): + """ + Computes mm(mat1, mat2) + mm(mat3, mat4) + """ + m1, n1, k1, layout1, mat1, mat2 = mm_args(mat1, mat2, layout=layout) + m2, n2, _, layout2, mat3, mat4 = mm_args(mat3, mat4, layout=layout) + # Optimization is optional, because we can always just not do the fusion + if ( + m1 * n1 == 0 + or m2 * n2 == 0 + or not V.graph.sizevars.statically_known_list_equals( + mat1.get_size(), mat3.get_size() + ) + or not V.graph.sizevars.statically_known_list_equals( + mat2.get_size(), mat4.get_size() + ) + ): + # TODO(jansel): support different K values when this is fixed: + # https://github.com/openai/triton/issues/967 + if m1 == m2 and n1 == n2: + V.graph.sizevars.guard_equals(m1, m2) + V.graph.sizevars.guard_equals(n1, n2) + return lowerings[aten.addmm](lowerings[aten.mm](mat3, mat4), mat1, mat2) + return lowerings[aten.add]( + lowerings[aten.mm](mat1, mat2), lowerings[aten.mm](mat3, mat4) + ) + + assert layout1 == layout2 + # options to tune from + choices = ( + [aten_mm_plus_mm.bind((mat1, mat2, mat3, mat4), layout1)] + if use_aten_gemm_kernels() + else [] + ) + if use_triton_template(layout1): + for config in mm_configs(): + # see https://github.com/openai/triton/issues/1298 + # BLOCK_K = K causes llvm error + if config.kwargs["BLOCK_K"] < k1: + mm_plus_mm_template.maybe_append_choice( + choices, + (mat1, mat2, mat3, mat4), + layout1, + **mm_options(config, k1, layout1), + ) + + return autotune_select_algorithm( + "mm_plus_mm", choices, [mat1, mat2, mat3, mat4], layout1 + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/unpack_mixed_mm.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/unpack_mixed_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..a8da948bf861b90159b2f342dccad6e616cd740c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/kernel/unpack_mixed_mm.py @@ -0,0 +1,82 @@ +import logging +from typing import List + +from ..select_algorithm import autotune_select_algorithm, ChoiceCaller, TritonTemplate +from .mm_common import mm_args, mm_configs, mm_grid, mm_options + +log = logging.getLogger(__name__) + +uint4x2_mixed_mm_template = TritonTemplate( + name="uint4x2_mixed_mm", + grid=mm_grid, + source=r""" +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + B = B + (rk[:, None]//2 * stride_bk + rbn[None, :] * stride_bn) + b_shifts = 4*(rk%2) + b_subs = 8*(1-(rk%2)) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.) + b = tl.load(B, mask=rk[:, None] < k, other=0.) + b = ((b >> b_shifts[:, None]) & 0xF) - 8 + b = b.to(B_PROLOGUE_CAST_TYPE) + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + A += BLOCK_K * stride_ak + B += BLOCK_K//2 * stride_bk + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask")}} +""", +) + + +def tuned_uint4x2_mixed_mm(mat1, mat2, mat2_mm_shape, mat2_dtype): + m, n, k, layout, mat1, mat2 = mm_args(mat1, mat2, layout=None, use_4x2_dim=True) + choices: List[ChoiceCaller] = [] + b_prologue_cast_type = f"tl.{mat2_dtype}".replace("torch.", "") + for config in mm_configs(m, n, k): + uint4x2_mixed_mm_template.maybe_append_choice( + choices, + (mat1, mat2), + layout, + **mm_options(config, k, layout, b_prologue_cast_type), + ) + return autotune_select_algorithm("uint4x2_mixed_mm", choices, [mat1, mat2], layout) diff --git a/llava_next/lib/python3.10/site-packages/torch/_lazy/__init__.py b/llava_next/lib/python3.10/site-packages/torch/_lazy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..249ce9b1157829d47d8fd833068de7e4da54cf1c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_lazy/__init__.py @@ -0,0 +1,55 @@ +import threading + +import torch._C._lazy +from torch.utils._pytree import tree_flatten, tree_unflatten + +from .closure import add_step_closure, run_step_closures + + +def mark_step(device: str = "", wait=False): + """Triggers a mark step, which amounts to + - collecting a group of 'live' lazy tensors to index into the compilation cache + (lowering/compiling their IR graphs if not cached) + - kicking off execution of the compiled function + - (optionally, wait=True) waiting for cpu-side execution to complete (does not sync the accelerator) + """ + # TODO(whc) expand this to include backend hooks and align with XLA backend needs + torch._C._lazy._mark_step(device, [], wait=wait) + + run_step_closures() + + +def wait_device_ops(devices=None): + """Waits for all the async operations on the given devices to complete. + Args: + devices (string..., optional): The devices whose async ops need to be waited + for. If empty, all the local devices will be waited for. + """ + if devices is None: + devices = [] + torch._C._lazy._wait_device_ops(devices=devices) + + +def sync_multi(tensors, devices): + """ + Sync the list of lazy tensors so there IR get lowered for the activate backend + and the compiled computation graph get cached. + """ + torch._C._lazy._sync_multi(tensors, devices) + + +def get_tensor_id(tensor): + """Return a unique id of the lazy tensor maintained by LTC""" + return torch._C._lazy._get_tensor_id(tensor) + + +def to_cpu(tensors, devices=None): + devices = devices or ["lazy"] + + flattened, spec = tree_flatten(tensors) + sync_multi(flattened, devices) + return tree_unflatten([t.to("cpu") for t in flattened], spec) + + +def save(tensors, *args, **kwargs): + torch.save(to_cpu(tensors), *args, **kwargs) diff --git a/llava_next/lib/python3.10/site-packages/torch/_lazy/closure.py b/llava_next/lib/python3.10/site-packages/torch/_lazy/closure.py new file mode 100644 index 0000000000000000000000000000000000000000..07f1055ee82783643bf5e57c8713d90aa1d15df6 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_lazy/closure.py @@ -0,0 +1,134 @@ +import os +import threading +from queue import Empty as EmptyQueue, Queue + +from torch._lazy.device_context import get_device_context + + +class ClosureHandler: + def __init__(self): + pass + + def run(self, closure): + """Run closure function + + Args: + closure: callable function to run + """ + closure() + + def __call__(self, closures): + for closure in closures: + self.run(closure) + + +class AsyncClosureHandler(ClosureHandler): + """Handler for Asynchronous Step Closures + Args: + max_queue_size: The maximum length of the closure queue after which + the training loop will block until closures are evaluated. + By default, a reasonable limit of a maximum of 100 on the queue. + This value can be set using the `XLA_MAX_ASYNC_QUEUE` environment + variable. + """ + + def __init__(self, max_queue_size=100): + super().__init__() + self._closure_queue: Queue = Queue( + int(os.environ.get("LTC_MAX_ASYNC_QUEUE", max_queue_size)) + ) + self._closure_exception: Queue = Queue() + self._closure_lock = threading.Lock() + self._closure_event_loop_finished = threading.Event() + self._closure_event_loop = None + + def start_event_loop(self): + """Start closure event loop if not started""" + if self._closure_event_loop is None: + + def event_loop(): + # Run loop until closure event is set and closure queue is empty + while True: + try: + closure = self._closure_queue.get(block=True, timeout=3) + closure() + self._closure_queue.task_done() + except EmptyQueue: + with self._closure_lock: + if self._closure_queue.empty(): + self._closure_event_loop_finished.set() + return + except Exception as e: + self._closure_exception.put(e) + return + + self._closure_event_loop = threading.Thread(target=event_loop) + self._closure_event_loop.start() + + def run(self, closure): + with self._closure_lock: + self._closure_queue.put(closure, block=True) + if ( + self._closure_event_loop is None + or not self._closure_event_loop.is_alive() + ): + try: + e = self._closure_exception.get(block=False) + raise RuntimeError( + "Cannot run asynchronous closure due to previously raised exception" + ) from e + except EmptyQueue: + self._closure_event_loop = None + self.start_event_loop() + + +def add_step_closure(closure, args=(), run_async=False): + """Adds a closure to the list of the ones to be run at the end of the step. + Many times during model training there is the need to print/report (print to + console, post to tensorboard, etc...) information which require the content of + intermediary tensors to be inspected. + Inspecting different tensors content in different points of the model code + requires many executions and typically causes performance issues. + Adding a step closure will ensure that it will be run after the barrier, when + all the live tensors will be already materialized to device data. + Live tensors which will include the ones captured by the closure arguments. + So using `add_step_closure()` will ensure a single execution will be + performed, even when multiple closures are queued, requiring multiple tensors + to be inspected. + Step closures will be run sequentially in the order they have been queued. + Note that even though using this API the execution will be optimized, it is + advised to throttle the printing/reporting events once every N steps. + Args: + closure (callable): The function to be called. + args (tuple): The arguments to be passed to the closure. + run_async: If True, run the closure asynchronously. + """ + devctx = get_device_context() + closures_type = "async_step_closures" if run_async else "step_closures" + step_closures = getattr(devctx, closures_type, None) + if step_closures is None: + step_closures = [] + setattr(devctx, closures_type, step_closures) + step_closures.append(lambda a=args: closure(*a)) + + +def run_step_closures(): + devctx = get_device_context() + async_step_closures = getattr(devctx, "async_step_closures", None) + if async_step_closures is not None: + devctx.async_step_closures = [] + async_closure_handler = getattr(devctx, "async_closure_handler", None) + if async_closure_handler is None: + async_closure_handler = AsyncClosureHandler() + devctx.async_closure_handler = async_closure_handler + async_closure_handler(async_step_closures) + + step_closures = getattr(devctx, "step_closures", None) + if step_closures is not None: + devctx.step_closures = [] + closure_handler = getattr(devctx, "closure_handler", None) + if closure_handler is None: + closure_handler = ClosureHandler() + devctx.closure_handler = closure_handler + closure_handler(step_closures) + return devctx diff --git a/llava_next/lib/python3.10/site-packages/torch/_lazy/computation.py b/llava_next/lib/python3.10/site-packages/torch/_lazy/computation.py new file mode 100644 index 0000000000000000000000000000000000000000..27b73c42e5c0de39e5112f717796cfce5d808bc1 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_lazy/computation.py @@ -0,0 +1,26 @@ +import torch._C._lazy +import torch._C._lazy_ts_backend + + +def get_tensors_ts_device_data_node(tensors): + """Return tensor ids and eager tensors for DeviceData nodes in the + IR for the passed in lazy tensors. + + TODO: This API is currently ts backend specific. We are working on + generalizing it to all backends including XLA. + """ + return torch._C._lazy_ts_backend._get_tensors_ts_device_data_node(tensors) + + +def get_graph_hash(tensors): + """Return the graph hash for the passed in lazy tensors""" + return torch._C._lazy._get_graph_hash(tensors) + + +def run_cached_graph(hash_str, graph_inputs): + """Running the cached computation graph with the given inputs + + TODO: This API is currently ts backend specific. We are working on + generalizing it to all backends including XLA. + """ + return torch._C._lazy_ts_backend._run_cached_graph(hash_str, graph_inputs) diff --git a/llava_next/lib/python3.10/site-packages/torch/_lazy/config.py b/llava_next/lib/python3.10/site-packages/torch/_lazy/config.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a4d1dd24f8dbf505995982bbb33b8d90d3de2e --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_lazy/config.py @@ -0,0 +1,16 @@ +import torch._C._lazy + + +def get_force_fallback(): + """Get the config used to force LTC fallback""" + return torch._C._lazy._get_force_fallback() + + +def set_force_fallback(configval): + """Set the config used to force LTC fallback""" + torch._C._lazy._set_force_fallback(configval) + + +def set_reuse_ir(val: bool): + """Set the config to reuse IR nodes for faster tracing""" + torch._C._lazy._set_reuse_ir(val) diff --git a/llava_next/lib/python3.10/site-packages/torch/_lazy/device_context.py b/llava_next/lib/python3.10/site-packages/torch/_lazy/device_context.py new file mode 100644 index 0000000000000000000000000000000000000000..840c7f8e50d039c9b72f31b16e8d69f706920534 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_lazy/device_context.py @@ -0,0 +1,25 @@ +import threading +from typing import Any, Dict + +import torch._C._lazy + + +class DeviceContext: + _CONTEXTS: Dict[str, Any] = dict() + _CONTEXTS_LOCK = threading.Lock() + + def __init__(self, device): + self.device = device + + +def get_device_context(device=None): + if device is None: + device = torch._C._lazy._get_default_device_type() + else: + device = str(device) + with DeviceContext._CONTEXTS_LOCK: + devctx = DeviceContext._CONTEXTS.get(device, None) + if devctx is None: + devctx = DeviceContext(device) + DeviceContext._CONTEXTS[device] = devctx + return devctx diff --git a/llava_next/lib/python3.10/site-packages/torch/_lazy/extract_compiled_graph.py b/llava_next/lib/python3.10/site-packages/torch/_lazy/extract_compiled_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..033d000c69d858aa1b8264d90c7d3e984229eb23 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_lazy/extract_compiled_graph.py @@ -0,0 +1,223 @@ +import copy +import dataclasses +import itertools +import os +from typing import Any, Callable, Dict, List + +import torch +import torch._lazy as lazy +import torch._lazy.metrics as metrics +from torch import fx +from torch._lazy import computation, debug as lazy_debug +from torch._lazy.tensor_factory_functions import tensor_factory_functions + +debug = os.environ.get("debug_extract_compiled_graph") is not None + + +@dataclasses.dataclass +class GraphInputMatcher: + """ + The GraphInputMatcher class setup the graph inputs for future calls after lazy tracing. + Specifically, those graph inputs corresponding to method parameters should be replaced with the + arguments for the current call. + + tensor_id_to_arg_idx maps the tensor id to the parameter index. + graph_input_tensor_ids, graph_input_ivalues list the tensor_id and ivalue for each of the + TS/XLA graph inputs. + """ + + tensor_id_to_arg_idx: Dict[int, int] + graph_input_tensor_ids: List[int] + # there are 2 categories of graph_input_tensors. + # Category 1: those whose id are not found in tensor_id_to_arg_idx. These are + # most likely const tensors and we can get its content from graph_input_tensors + # Category 2: those whose id are found in tensor_id_to_arg_idx. We should get + # the tensor from method arguments + graph_input_ivalues: List[Any] + + # get the real graph input tensors + def __call__(self, args): + real_input = [] + for tensor_id, traced_ivalue in zip( + self.graph_input_tensor_ids, self.graph_input_ivalues + ): + arg_idx = self.tensor_id_to_arg_idx.get(tensor_id, None) + if arg_idx is None: + inp = traced_ivalue + else: + inp = args[arg_idx] + real_input.append(inp) + return real_input + + +class ReturnValueHandler: + r""" + When ltc_sync_multi is called on multi tensors, the compiled graph + will contain output only for unique tensors - if a tensor appears multiple + times in the input to _ltc_sync_multi, only the first occurance matters. + + However from python level, we still expect multi tensors returned with duplciation + even if the TS graph dedup the output. e.g. for method: + + def forward(self, a): + return a, a + + the TS graph captured by LTC will return a single tensor, but Python method expects 2. + + This class dedup the lazy tensors first to get the index that will be used + to duplicate the eager tensors later. + """ + + def __init__(self, lazy_out_list): + self.index: List[List[int]] = [] + self.total_count = len(lazy_out_list) + + tensor_id_to_idx: Dict[int, int] = {} + for dup_idx, lazy_tensor in enumerate(lazy_out_list): + uniq_idx = tensor_id_to_idx.get(id(lazy_tensor), None) + if uniq_idx is not None: + self.index[uniq_idx].append(dup_idx) + else: + uniq_idx = len(self.index) + self.index.append([dup_idx]) + tensor_id_to_idx[id(lazy_tensor)] = uniq_idx + + def duplicate_eager_tensors(self, eager_tensor_list): + duplicated_list = [None] * self.total_count + assert len(eager_tensor_list) == len(self.index) + + for uniq_idx, eager_tensor in enumerate(eager_tensor_list): + for dup_idx in self.index[uniq_idx]: + duplicated_list[dup_idx] = eager_tensor + return duplicated_list + + +def force_lazy_device(model: fx.GraphModule): + """ + Factory methods in a Fx graph may create tensors for a specific eager devices. + If we take no actions, those eager tensors will be mixed with lazy tensors and + cause crash. This method overwrite those eager device to lazy device. + """ + + def tolazydevice(dev): + if isinstance(dev, torch.device): + return torch.device("lazy", index=dev.index) + return dev + + def hasDeviceArg(args, kwargs): + return any( + isinstance(arg, torch.device) + for arg in itertools.chain(args, kwargs.values()) + ) + + for nd in model.graph.nodes: + nd.args = tuple(tolazydevice(arg) for arg in nd.args) + nd.kwargs = {k: tolazydevice(v) for k, v in nd.kwargs.items()} + + # For torchbench like yolov3, hf_Bart, dynamo generates Fx graph that return + # eager tensors on the default device + # (check https://gist.github.com/shunting314/eabdf6c769c59bc384469717b8f9bb7f for yolove, + # and https://gist.github.com/shunting314/8d5e2d9348a3258959d3954186c48814 for hf_Bart). + # To force those tensors on the lazy device, we can not simply override + # the device argument since there is no explicit device argument. + # What we are doing here is, for the list of covered tensor factory methods + # we add a lazy device argument explicity. + # + # TODO: This solution is no ideal since we may miss some factory methods. In future + # when we support lazy mode, this method can be replaced by that. + if nd.target in tensor_factory_functions and not hasDeviceArg( + nd.args, nd.kwargs + ): + kwargs = dict(nd.kwargs) # nd.kwargs is immutable. make a mutable copy. + kwargs["device"] = torch.device("lazy") + nd.kwargs = kwargs + + model.recompile() + + +def get_fallback_ops(): + fallback_ops = [] + for opname in metrics.counter_names(): + if "aten::" not in opname: + continue + val = int(metrics.counter_value(opname)) + if val > 0: + fallback_ops.append(f"{opname}={val}") + + return fallback_ops + + +def extract_compiled_graph(model: fx.GraphModule, example_inputs) -> Callable: + """ + Optimize an eager model with LTC and returns a wrapper to execute the + compiled graph directly without retracing. It depends on other mechanisms + like TorchDynamo guards to guarantee the returned wrapper is only called + when it's safe. + """ + lazy_args = [arg.to(device="lazy") for arg in example_inputs] + args_tensor_ids = [lazy.get_tensor_id(lazy_arg) for lazy_arg in lazy_args] + tensor_id_to_arg_idx = {tensor_id: i for i, tensor_id in enumerate(args_tensor_ids)} + lazy_model = copy.deepcopy(model).to(device=torch.device("lazy")) + force_lazy_device(lazy_model) + + # This line executes lazy tracing and enable us extracting compiled graph later + metrics.reset() + lazy_out = lazy_model(*lazy_args) + fallback_ops = get_fallback_ops() + metrics.reset() + + if len(fallback_ops) > 0: + raise RuntimeError( + f"Fail to extact the compiled graph because of fallback: {','.join(fallback_ops)}" + ) + + if not isinstance(lazy_out, (tuple, list)): + lazy_out = (lazy_out,) + + args_and_out = tuple(lazy_args) + tuple(lazy_out) + return_value_handler = ReturnValueHandler(args_and_out) + if debug: + print("Fx code:\n", model.code) + print("LTC IR:", lazy_debug.dump_ir(args_and_out, "text")) + + # TODO: this part is TS backend specific for now and will be generalized to + # support XLA + ( + graph_input_tensor_ids, + graph_input_ivalues, + ) = computation.get_tensors_ts_device_data_node(args_and_out) + assert len(graph_input_tensor_ids) == len(graph_input_ivalues) + graph_input_matcher = GraphInputMatcher( + tensor_id_to_arg_idx, graph_input_tensor_ids, graph_input_ivalues + ) + + graph_hash = computation.get_graph_hash(args_and_out) + + if debug: + print("graph_hash", graph_hash) + print(f"args_tensor_ids {args_tensor_ids}") + print("tensor ids from device data:", graph_input_tensor_ids) + + # sync the list of output tensors so the computation graph for these + # tensors will be cached. Those computation graphs can be retrieved + # by graph hash later. + lazy.sync_multi(args_and_out, []) + + def optimized_mod(*args): + if len(args_and_out) == 0: + return () + graph_input = graph_input_matcher(args) + res = return_value_handler.duplicate_eager_tensors( + computation.run_cached_graph(graph_hash, graph_input) + ) + + assert len(res) == len(args_and_out) + for i, arg in enumerate(args): + # only copy those tensors that get inplace updated + if arg is not res[i]: + arg.copy_(res[i]) + + # skip the args + return res[len(args) :] + + return optimized_mod diff --git a/llava_next/lib/python3.10/site-packages/torch/_lazy/metrics.py b/llava_next/lib/python3.10/site-packages/torch/_lazy/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7db730556779a353a1bb9f4b2529464d4bfc95 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_lazy/metrics.py @@ -0,0 +1,21 @@ +import torch._C._lazy + + +def reset(): + """Resets all metric counters.""" + torch._C._lazy._reset_metrics() + + +def counter_names(): + """Retrieves all the currently active counter names.""" + return torch._C._lazy._counter_names() + + +def counter_value(name: str): + """Return the value of the counter with the speficied name""" + return torch._C._lazy._counter_value(name) + + +def metrics_report(): + """Return the combined (lazy core and backend) metric report""" + return torch._C._lazy._metrics_report() diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/__init__.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40369d62a1359c1adf7be9a40dfbb845b8ab4eec Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/__init__.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/_percentile.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/_percentile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..105c4bb2b0f9bc482b061ad43e24b9633538c882 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/_percentile.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/bilateral.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/bilateral.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..685acebb1b872922723f57ba7e7e02ecda54496e Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/bilateral.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/generic.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/generic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..472e2b60025df28e0bee2d72ccee6b47e3b55283 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/__pycache__/generic.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/tests/__pycache__/test_rank.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/tests/__pycache__/test_rank.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa2778336c5766e97ea38192a0b416c233de7fbd Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/tests/__pycache__/test_rank.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__init__.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_correlate.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_correlate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..868736084797f359aa802c789b7cbf789f9363b4 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_correlate.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_edges.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_edges.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0a911577462bd53f611c09cc1c22995556579e6 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_edges.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_fft_based.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_fft_based.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9a9cfc6e6a42c433f23736d6b46d983432246ad Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_fft_based.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_gaussian.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_gaussian.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1be59d7adeceeccee5e27798a80760483815f0fb Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_gaussian.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_lpi_filter.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_lpi_filter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12da17154fe9215c5a892237d00675478debd3ac Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_lpi_filter.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_ridges.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_ridges.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4073d966e5e8cfb9d60d831a99de095f7c38644 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_ridges.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_thresholding.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_thresholding.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8e183bae5cbc1082fc87f84ce6ce5119ec2dbd0 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_thresholding.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_unsharp_mask.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_unsharp_mask.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c79abd7b1616b47ca9afd5ac2508f33504a6721 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/__pycache__/test_unsharp_mask.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_correlate.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_correlate.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f705c505bf7ba1267e50c0936021f759c5b08f --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_correlate.py @@ -0,0 +1,70 @@ +import numpy as np +import pytest +from numpy.testing import assert_equal +from scipy import ndimage as ndi + +from skimage._shared.utils import _supported_float_type +from skimage.filters import correlate_sparse + + +def test_correlate_sparse_valid_mode(): + image = np.array( + [ + [0, 0, 1, 3, 5], + [0, 1, 4, 3, 4], + [1, 2, 5, 4, 1], + [2, 4, 5, 2, 1], + [4, 5, 1, 0, 0], + ], + dtype=float, + ) + + kernel = np.array([0, 1, 2, 4, 8, 16, 32, 64, 128]).reshape((3, 3)) + + cs_output = correlate_sparse(image, kernel, mode="valid") + ndi_output = ndi.correlate(image, kernel, mode='wrap') + ndi_output = ndi_output[1:4, 1:4] + + assert_equal(cs_output, ndi_output) + + +@pytest.mark.parametrize("mode", ["nearest", "reflect", "mirror"]) +@pytest.mark.parametrize( + "dtype", [np.uint16, np.int32, np.float16, np.float32, np.float64] +) +def test_correlate_sparse(mode, dtype): + image = np.array( + [ + [0, 0, 1, 3, 5], + [0, 1, 4, 3, 4], + [1, 2, 5, 4, 1], + [2, 4, 5, 2, 1], + [4, 5, 1, 0, 0], + ], + dtype=dtype, + ) + + kernel = np.array([0, 1, 2, 4, 8, 16, 32, 64, 128]).reshape((3, 3)) + + cs_output = correlate_sparse(image, kernel, mode=mode) + assert cs_output.dtype == _supported_float_type(image.dtype) + ndi_output = ndi.correlate(image.astype(float, copy=False), kernel, mode=mode) + assert_equal(cs_output, ndi_output) + + +@pytest.mark.parametrize("mode", ["nearest", "reflect", "mirror"]) +def test_correlate_sparse_invalid_kernel(mode): + image = np.array( + [ + [0, 0, 1, 3, 5], + [0, 1, 4, 3, 4], + [1, 2, 5, 4, 1], + [2, 4, 5, 2, 1], + [4, 5, 1, 0, 0], + ], + dtype=float, + ) + # invalid kernel size + invalid_kernel = np.array([0, 1, 2, 4]).reshape((2, 2)) + with pytest.raises(ValueError): + correlate_sparse(image, invalid_kernel, mode=mode) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_edges.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_edges.py new file mode 100644 index 0000000000000000000000000000000000000000..85ccfd002e93d48db8552dc3d9480bb4cb5711c0 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_edges.py @@ -0,0 +1,665 @@ +import numpy as np +import pytest +from numpy.testing import assert_, assert_allclose, assert_array_almost_equal + +from skimage import data, filters +from skimage._shared.utils import _supported_float_type +from skimage.filters.edges import _mask_filter_result + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_roberts_zeros(dtype): + """Roberts' filter on an array of all zeros.""" + result = filters.roberts(np.zeros((10, 10), dtype=dtype), np.ones((10, 10), bool)) + assert result.dtype == _supported_float_type(dtype) + assert np.all(result == 0) + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_roberts_diagonal1(dtype): + """Roberts' filter on a diagonal edge should be a diagonal line.""" + image = np.tri(10, 10, 0, dtype=dtype) + expected = ~( + np.tri(10, 10, -1).astype(bool) | np.tri(10, 10, -2).astype(bool).transpose() + ) + expected[-1, -1] = 0 # due to 'reflect' & image shape, last pixel not edge + result = filters.roberts(image) + assert result.dtype == _supported_float_type(dtype) + assert_array_almost_equal(result.astype(bool), expected) + + +@pytest.mark.parametrize( + 'function_name', ['farid', 'laplace', 'prewitt', 'roberts', 'scharr', 'sobel'] +) +def test_int_rescaling(function_name): + """Basic test that uint8 inputs get rescaled from [0, 255] to [0, 1.] + + The output of any of these filters should be within roughly a factor of + two of the input range. For integer inputs, rescaling to floats in + [0.0, 1.0] should occur, so just verify outputs are not > 2.0. + """ + img = data.coins()[:128, :128] + func = getattr(filters, function_name) + filtered = func(img) + assert filtered.max() <= 2.0 + + +def test_roberts_diagonal2(): + """Roberts' filter on a diagonal edge should be a diagonal line.""" + image = np.rot90(np.tri(10, 10, 0), 3) + expected = ~np.rot90( + np.tri(10, 10, -1).astype(bool) | np.tri(10, 10, -2).astype(bool).transpose() + ) + expected = _mask_filter_result(expected, None) + result = filters.roberts(image).astype(bool) + assert_array_almost_equal(result, expected) + + +def test_sobel_zeros(): + """Sobel on an array of all zeros.""" + result = filters.sobel(np.zeros((10, 10)), np.ones((10, 10), bool)) + assert np.all(result == 0) + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_sobel_mask(dtype): + """Sobel on a masked array should be zero.""" + result = filters.sobel( + np.random.uniform(size=(10, 10)).astype(dtype), np.zeros((10, 10), dtype=bool) + ) + assert result.dtype == _supported_float_type(dtype) + assert np.all(result == 0) + + +def test_sobel_horizontal(): + """Sobel on a horizontal edge should be a horizontal line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.sobel(image) * np.sqrt(2) + # Check if result match transform direction + assert_allclose(result[i == 0], 1) + assert np.all(result[np.abs(i) > 1] == 0) + + +def test_sobel_vertical(): + """Sobel on a vertical edge should be a vertical line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.sobel(image) * np.sqrt(2) + assert np.all(result[j == 0] == 1) + assert np.all(result[np.abs(j) > 1] == 0) + + +def test_sobel_h_zeros(): + """Horizontal sobel on an array of all zeros.""" + result = filters.sobel_h(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) + assert np.all(result == 0) + + +def test_sobel_h_mask(): + """Horizontal Sobel on a masked array should be zero.""" + result = filters.sobel_h( + np.random.uniform(size=(10, 10)), np.zeros((10, 10), dtype=bool) + ) + assert np.all(result == 0) + + +def test_sobel_h_horizontal(): + """Horizontal Sobel on an edge should be a horizontal line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.sobel_h(image) + # Check if result match transform direction + assert np.all(result[i == 0] == 1) + assert np.all(result[np.abs(i) > 1] == 0) + + +def test_sobel_h_vertical(): + """Horizontal Sobel on a vertical edge should be zero.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) * np.sqrt(2) + result = filters.sobel_h(image) + assert_allclose(result, 0, atol=1e-10) + + +def test_sobel_v_zeros(): + """Vertical sobel on an array of all zeros.""" + result = filters.sobel_v(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) + assert_allclose(result, 0) + + +def test_sobel_v_mask(): + """Vertical Sobel on a masked array should be zero.""" + result = filters.sobel_v( + np.random.uniform(size=(10, 10)), np.zeros((10, 10), dtype=bool) + ) + assert_allclose(result, 0) + + +def test_sobel_v_vertical(): + """Vertical Sobel on an edge should be a vertical line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.sobel_v(image) + # Check if result match transform direction + assert np.all(result[j == 0] == 1) + assert np.all(result[np.abs(j) > 1] == 0) + + +def test_sobel_v_horizontal(): + """vertical Sobel on a horizontal edge should be zero.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.sobel_v(image) + assert_allclose(result, 0) + + +def test_scharr_zeros(): + """Scharr on an array of all zeros.""" + result = filters.scharr(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) + assert np.all(result < 1e-16) + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_scharr_mask(dtype): + """Scharr on a masked array should be zero.""" + result = filters.scharr( + np.random.uniform(size=(10, 10)).astype(dtype), np.zeros((10, 10), dtype=bool) + ) + assert result.dtype == _supported_float_type(dtype) + assert_allclose(result, 0) + + +def test_scharr_horizontal(): + """Scharr on an edge should be a horizontal line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.scharr(image) * np.sqrt(2) + # Check if result match transform direction + assert_allclose(result[i == 0], 1) + assert np.all(result[np.abs(i) > 1] == 0) + + +def test_scharr_vertical(): + """Scharr on a vertical edge should be a vertical line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.scharr(image) * np.sqrt(2) + assert_allclose(result[j == 0], 1) + assert np.all(result[np.abs(j) > 1] == 0) + + +def test_scharr_h_zeros(): + """Horizontal Scharr on an array of all zeros.""" + result = filters.scharr_h(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) + assert_allclose(result, 0) + + +def test_scharr_h_mask(): + """Horizontal Scharr on a masked array should be zero.""" + result = filters.scharr_h( + np.random.uniform(size=(10, 10)), np.zeros((10, 10), dtype=bool) + ) + assert_allclose(result, 0) + + +def test_scharr_h_horizontal(): + """Horizontal Scharr on an edge should be a horizontal line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.scharr_h(image) + # Check if result match transform direction + assert np.all(result[i == 0] == 1) + assert np.all(result[np.abs(i) > 1] == 0) + + +def test_scharr_h_vertical(): + """Horizontal Scharr on a vertical edge should be zero.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.scharr_h(image) + assert_allclose(result, 0) + + +def test_scharr_v_zeros(): + """Vertical Scharr on an array of all zeros.""" + result = filters.scharr_v(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) + assert_allclose(result, 0) + + +def test_scharr_v_mask(): + """Vertical Scharr on a masked array should be zero.""" + result = filters.scharr_v( + np.random.uniform(size=(10, 10)), np.zeros((10, 10), dtype=bool) + ) + assert_allclose(result, 0) + + +def test_scharr_v_vertical(): + """Vertical Scharr on an edge should be a vertical line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.scharr_v(image) + # Check if result match transform direction + assert np.all(result[j == 0] == 1) + assert np.all(result[np.abs(j) > 1] == 0) + + +def test_scharr_v_horizontal(): + """vertical Scharr on a horizontal edge should be zero.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.scharr_v(image) + assert_allclose(result, 0) + + +def test_prewitt_zeros(): + """Prewitt on an array of all zeros.""" + result = filters.prewitt(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) + assert_allclose(result, 0) + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_prewitt_mask(dtype): + """Prewitt on a masked array should be zero.""" + result = filters.prewitt( + np.random.uniform(size=(10, 10)).astype(dtype), np.zeros((10, 10), dtype=bool) + ) + assert result.dtype == _supported_float_type(dtype) + assert_allclose(np.abs(result), 0) + + +def test_prewitt_horizontal(): + """Prewitt on an edge should be a horizontal line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.prewitt(image) * np.sqrt(2) + # Check if result match transform direction + assert np.all(result[i == 0] == 1) + assert_allclose(result[np.abs(i) > 1], 0, atol=1e-10) + + +def test_prewitt_vertical(): + """Prewitt on a vertical edge should be a vertical line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.prewitt(image) * np.sqrt(2) + assert_allclose(result[j == 0], 1) + assert_allclose(result[np.abs(j) > 1], 0, atol=1e-10) + + +def test_prewitt_h_zeros(): + """Horizontal prewitt on an array of all zeros.""" + result = filters.prewitt_h(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) + assert_allclose(result, 0) + + +def test_prewitt_h_mask(): + """Horizontal prewitt on a masked array should be zero.""" + result = filters.prewitt_h( + np.random.uniform(size=(10, 10)), np.zeros((10, 10), dtype=bool) + ) + assert_allclose(result, 0) + + +def test_prewitt_h_horizontal(): + """Horizontal prewitt on an edge should be a horizontal line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.prewitt_h(image) + # Check if result match transform direction + assert np.all(result[i == 0] == 1) + assert_allclose(result[np.abs(i) > 1], 0, atol=1e-10) + + +def test_prewitt_h_vertical(): + """Horizontal prewitt on a vertical edge should be zero.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.prewitt_h(image) + assert_allclose(result, 0, atol=1e-10) + + +def test_prewitt_v_zeros(): + """Vertical prewitt on an array of all zeros.""" + result = filters.prewitt_v(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) + assert_allclose(result, 0) + + +def test_prewitt_v_mask(): + """Vertical prewitt on a masked array should be zero.""" + result = filters.prewitt_v( + np.random.uniform(size=(10, 10)), np.zeros((10, 10), dtype=bool) + ) + assert_allclose(result, 0) + + +def test_prewitt_v_vertical(): + """Vertical prewitt on an edge should be a vertical line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.prewitt_v(image) + # Check if result match transform direction + assert np.all(result[j == 0] == 1) + assert_allclose(result[np.abs(j) > 1], 0, atol=1e-10) + + +def test_prewitt_v_horizontal(): + """Vertical prewitt on a horizontal edge should be zero.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.prewitt_v(image) + assert_allclose(result, 0) + + +def test_laplace_zeros(): + """Laplace on a square image.""" + # Create a synthetic 2D image + image = np.zeros((9, 9)) + image[3:-3, 3:-3] = 1 + result = filters.laplace(image) + check_result = np.array( + [ + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 2.0, 1.0, 2.0, -1.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 1.0, 0.0, 1.0, -1.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 2.0, 1.0, 2.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + ] + ) + assert_allclose(result, check_result) + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_laplace_mask(dtype): + """Laplace on a masked array should be zero.""" + # Create a synthetic 2D image + image = np.zeros((9, 9), dtype=dtype) + image[3:-3, 3:-3] = 1 + # Define the mask + result = filters.laplace(image, ksize=3, mask=np.zeros((9, 9), dtype=bool)) + assert result.dtype == _supported_float_type(dtype) + assert np.all(result == 0) + + +def test_farid_zeros(): + """Farid on an array of all zeros.""" + result = filters.farid(np.zeros((10, 10)), mask=np.ones((10, 10), dtype=bool)) + assert np.all(result == 0) + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_farid_mask(dtype): + """Farid on a masked array should be zero.""" + result = filters.farid( + np.random.uniform(size=(10, 10)).astype(dtype), + mask=np.zeros((10, 10), dtype=bool), + ) + assert result.dtype == _supported_float_type(dtype) + assert np.all(result == 0) + + +def test_farid_horizontal(): + """Farid on a horizontal edge should be a horizontal line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.farid(image) * np.sqrt(2) + # Check if result match transform direction + assert np.all(result[i == 0] == result[i == 0][0]) + assert_allclose(result[np.abs(i) > 2], 0, atol=1e-10) + + +def test_farid_vertical(): + """Farid on a vertical edge should be a vertical line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.farid(image) * np.sqrt(2) + assert np.all(result[j == 0] == result[j == 0][0]) + assert_allclose(result[np.abs(j) > 2], 0, atol=1e-10) + + +def test_farid_h_zeros(): + """Horizontal Farid on an array of all zeros.""" + result = filters.farid_h(np.zeros((10, 10)), mask=np.ones((10, 10), dtype=bool)) + assert np.all(result == 0) + + +def test_farid_h_mask(): + """Horizontal Farid on a masked array should be zero.""" + result = filters.farid_h( + np.random.uniform(size=(10, 10)), mask=np.zeros((10, 10), dtype=bool) + ) + assert np.all(result == 0) + + +def test_farid_h_horizontal(): + """Horizontal Farid on an edge should be a horizontal line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.farid_h(image) + # Check if result match transform direction + assert np.all(result[i == 0] == result[i == 0][0]) + assert_allclose(result[np.abs(i) > 2], 0, atol=1e-10) + + +def test_farid_h_vertical(): + """Horizontal Farid on a vertical edge should be zero.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) * np.sqrt(2) + result = filters.farid_h(image) + assert_allclose(result, 0, atol=1e-10) + + +def test_farid_v_zeros(): + """Vertical Farid on an array of all zeros.""" + result = filters.farid_v(np.zeros((10, 10)), mask=np.ones((10, 10), dtype=bool)) + assert_allclose(result, 0, atol=1e-10) + + +def test_farid_v_mask(): + """Vertical Farid on a masked array should be zero.""" + result = filters.farid_v( + np.random.uniform(size=(10, 10)), mask=np.zeros((10, 10), dtype=bool) + ) + assert_allclose(result, 0) + + +def test_farid_v_vertical(): + """Vertical Farid on an edge should be a vertical line.""" + i, j = np.mgrid[-5:6, -5:6] + image = (j >= 0).astype(float) + result = filters.farid_v(image) + # Check if result match transform direction + assert np.all(result[j == 0] == result[j == 0][0]) + assert_allclose(result[np.abs(j) > 2], 0, atol=1e-10) + + +def test_farid_v_horizontal(): + """vertical Farid on a horizontal edge should be zero.""" + i, j = np.mgrid[-5:6, -5:6] + image = (i >= 0).astype(float) + result = filters.farid_v(image) + assert_allclose(result, 0, atol=1e-10) + + +@pytest.mark.parametrize( + "grad_func", (filters.prewitt_h, filters.sobel_h, filters.scharr_h) +) +def test_horizontal_mask_line(grad_func): + """Horizontal edge filters mask pixels surrounding input mask.""" + vgrad, _ = np.mgrid[:1:11j, :1:11j] # vertical gradient with spacing 0.1 + vgrad[5, :] = 1 # bad horizontal line + + mask = np.ones_like(vgrad) + mask[5, :] = 0 # mask bad line + + expected = np.zeros_like(vgrad) + expected[1:-1, 1:-1] = 0.2 # constant gradient for most of image, + expected[4:7, 1:-1] = 0 # but line and neighbors masked + + result = grad_func(vgrad, mask) + assert_allclose(result, expected) + + +@pytest.mark.parametrize( + "grad_func", (filters.prewitt_v, filters.sobel_v, filters.scharr_v) +) +def test_vertical_mask_line(grad_func): + """Vertical edge filters mask pixels surrounding input mask.""" + _, hgrad = np.mgrid[:1:11j, :1:11j] # horizontal gradient with spacing 0.1 + hgrad[:, 5] = 1 # bad vertical line + + mask = np.ones_like(hgrad) + mask[:, 5] = 0 # mask bad line + + expected = np.zeros_like(hgrad) + expected[1:-1, 1:-1] = 0.2 # constant gradient for most of image, + expected[1:-1, 4:7] = 0 # but line and neighbors masked + + result = grad_func(hgrad, mask) + assert_allclose(result, expected) + + +# The below three constant 3x3x3 cubes were empirically found to maximise the +# output of each of their respective filters. We use them to test that the +# output of the filter on the blobs image matches expectation in terms of +# scale. + +# maximum Sobel 3D edge on axis 0 +MAX_SOBEL_0 = np.array( + [ + [[0, 0, 0], [0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0], [0, 0, 0]], + [[1, 1, 1], [1, 1, 1], [1, 1, 1]], + ], + dtype=float, +) + +# maximum Sobel 3D edge in magnitude +MAX_SOBEL_ND = np.array( + [ + [[1, 0, 0], [1, 0, 0], [1, 0, 0]], + [[1, 0, 0], [1, 1, 0], [1, 1, 0]], + [[1, 1, 0], [1, 1, 0], [1, 1, 0]], + ], + dtype=float, +) + +# maximum Scharr 3D edge in magnitude. This illustrates the better rotation +# invariance of the Scharr filter! +MAX_SCHARR_ND = np.array( + [ + [[0, 0, 0], [0, 0, 1], [0, 1, 1]], + [[0, 0, 1], [0, 1, 1], [0, 1, 1]], + [[0, 0, 1], [0, 1, 1], [1, 1, 1]], + ], + dtype=float, +) + +# maximum Farid 3D edge on axis 0 +MAX_FARID_0 = np.zeros((5, 5, 5), dtype=float) +MAX_FARID_0[2:, :, :] = 1 + +# maximum Farid 3D edge in magnitude (not necessarily the true maximum, +# but this was the empirical max over the blobs image as in the test below). +MAX_FARID_ND = np.array( + [ + [ + [1, 0, 0, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + ], + [ + [0, 0, 0, 0, 0], + [1, 1, 0, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + ], + [ + [0, 0, 0, 0, 0], + [1, 0, 0, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + ], + [ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [1, 0, 0, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 1], + ], + [ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [1, 1, 1, 1, 1], + ], + ], + dtype=float, +) + + +@pytest.mark.parametrize( + ('func', 'max_edge'), + [ + (filters.prewitt, MAX_SOBEL_ND), + (filters.sobel, MAX_SOBEL_ND), + (filters.scharr, MAX_SCHARR_ND), + (filters.farid, MAX_FARID_ND), + ], +) +def test_3d_edge_filters(func, max_edge): + blobs = data.binary_blobs(length=128, n_dim=3, rng=5) + edges = func(blobs) + center = max_edge.shape[0] // 2 + if center == 2: + # exact edge as defined in MAX_FARID_0 not present in blobs data + rtol = 1e-3 + else: + rtol = 1e-7 + assert_allclose(np.max(edges), func(max_edge)[center, center, center], rtol=rtol) + + +@pytest.mark.parametrize( + ('func', 'max_edge'), + [ + (filters.prewitt, MAX_SOBEL_0), + (filters.sobel, MAX_SOBEL_0), + (filters.scharr, MAX_SOBEL_0), + (filters.farid, MAX_FARID_0), + ], +) +def test_3d_edge_filters_single_axis(func, max_edge): + blobs = data.binary_blobs(length=128, n_dim=3, rng=5) + edges0 = func(blobs, axis=0) + center = max_edge.shape[0] // 2 + if center == 2: + # exact edge as defined in MAX_FARID_0 not present in blobs data + rtol = 1e-3 + else: + rtol = 1e-7 + assert_allclose( + np.max(edges0), func(max_edge, axis=0)[center, center, center], rtol=rtol + ) + + +@pytest.mark.parametrize( + 'detector', + [filters.sobel, filters.scharr, filters.prewitt, filters.roberts, filters.farid], +) +def test_range(detector): + """Output of edge detection should be in [0, 1]""" + image = np.random.random((100, 100)) + out = detector(image) + assert_(out.min() >= 0, f'Minimum of `{detector.__name__}` is smaller than 0.') + + assert_(out.max() <= 1, f'Maximum of `{detector.__name__}` is larger than 1.') diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_fft_based.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_fft_based.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcbcd699d33ce7105761607b2ffcbd3dd0f62ff --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_fft_based.py @@ -0,0 +1,318 @@ +import math + +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal +import scipy.fft as fftmodule + +from skimage._shared.utils import _supported_float_type +from skimage.data import astronaut, coins +from skimage.filters import butterworth +from skimage.filters._fft_based import _get_nd_butterworth_filter + + +def _fft_centered(x): + return fftmodule.fftshift(fftmodule.fftn(fftmodule.fftshift(x))) + + +@pytest.mark.parametrize( + 'dtype', [np.float16, np.float32, np.float64, np.uint8, np.int32] +) +@pytest.mark.parametrize('squared_butterworth', [False, True]) +def test_butterworth_2D_zeros_dtypes(dtype, squared_butterworth): + im = np.zeros((4, 4), dtype=dtype) + filtered = butterworth(im, squared_butterworth=squared_butterworth) + assert filtered.shape == im.shape + assert filtered.dtype == _supported_float_type(dtype) + assert_array_equal(im, filtered) + + +@pytest.mark.parametrize('squared_butterworth', [False, True]) +@pytest.mark.parametrize('high_pass', [False, True]) +# order chosen large enough that lowpass stopband always approaches 0 +@pytest.mark.parametrize('order', [6, 10]) +@pytest.mark.parametrize('cutoff', [0.2, 0.3]) +def test_butterworth_cutoff(cutoff, order, high_pass, squared_butterworth): + wfilt = _get_nd_butterworth_filter( + shape=(512, 512), + factor=cutoff, + order=order, + high_pass=high_pass, + real=False, + squared_butterworth=squared_butterworth, + ) + # select DC frequence on first axis to plot profile along a single axis + wfilt_profile = np.abs(wfilt[0]) + + # Empirical chosen to pass for order=6. Can use a smaller tolerance at + # higher orders. + tol = 0.3 / order + + # should have amplitude of ~1.0 in the center of the passband + if high_pass: + assert abs(wfilt_profile[wfilt_profile.size // 2] - 1.0) < tol + else: + assert abs(wfilt_profile[0] - 1.0) < tol + + # should be close to the expected amplitude at the cutoff frequency + f_cutoff = int(cutoff * wfilt.shape[0]) + if squared_butterworth: + # expect 0.5 at the cutoff + assert abs(wfilt_profile[f_cutoff] - 0.5) < tol + else: + # expect 1/sqrt(2) at the cutoff + assert abs(wfilt_profile[f_cutoff] - 1 / math.sqrt(2)) < tol + + +@pytest.mark.parametrize('cutoff', [-0.01, 0.51]) +def test_butterworth_invalid_cutoff(cutoff): + with pytest.raises(ValueError): + butterworth(np.ones((4, 4)), cutoff_frequency_ratio=cutoff) + + +@pytest.mark.parametrize("high_pass", [True, False]) +@pytest.mark.parametrize('squared_butterworth', [False, True]) +def test_butterworth_2D(high_pass, squared_butterworth): + # rough check of high-pass vs. low-pass behavior via relative energy + + # adjust specified order so that lowpass stopband approaches 0 + order = 3 if squared_butterworth else 6 + + im = np.random.randn(64, 128) + filtered = butterworth( + im, + cutoff_frequency_ratio=0.20, + order=order, + high_pass=high_pass, + squared_butterworth=squared_butterworth, + ) + + # Compute the energy at the outer edges of the Fourier domain + # before and after filtering. + im_fft = _fft_centered(im) + im_fft = np.real(im_fft * np.conj(im_fft)) + filtered_fft = _fft_centered(filtered) + filtered_fft = np.real(filtered_fft * np.conj(filtered_fft)) + outer_mask = np.ones(im.shape, dtype=bool) + outer_mask[4:-4, 4:-4] = 0 + abs_filt_outer = filtered_fft[outer_mask].mean() + abs_im_outer = im_fft[outer_mask].mean() + + # Compute energy near the center of the Fourier domain + inner_sl = tuple(slice(s // 2 - 4, s // 2 + 4) for s in im.shape) + abs_filt_inner = filtered_fft[inner_sl].mean() + abs_im_inner = im_fft[inner_sl].mean() + + if high_pass: + assert abs_filt_outer > 0.9 * abs_im_outer + assert abs_filt_inner < 0.1 * abs_im_inner + else: + assert abs_filt_outer < 0.1 * abs_im_outer + assert abs_filt_inner > 0.9 * abs_im_inner + + +@pytest.mark.parametrize("high_pass", [True, False]) +@pytest.mark.parametrize('dtype', [np.float32, np.float64]) +@pytest.mark.parametrize('squared_butterworth', [False, True]) +def test_butterworth_2D_realfft(high_pass, dtype, squared_butterworth): + """Filtering a real-valued array is equivalent to filtering a + complex-valued array where the imaginary part is zero. + """ + im = np.random.randn(32, 64).astype(dtype) + kwargs = dict( + cutoff_frequency_ratio=0.20, + high_pass=high_pass, + squared_butterworth=squared_butterworth, + ) + + expected_dtype = _supported_float_type(im.dtype) + filtered_real = butterworth(im, **kwargs) + assert filtered_real.dtype == expected_dtype + + cplx_dtype = np.promote_types(im.dtype, np.complex64) + filtered_cplx = butterworth(im.astype(cplx_dtype), **kwargs) + assert filtered_cplx.real.dtype == expected_dtype + + if expected_dtype == np.float64: + rtol = atol = 1e-13 + else: + rtol = atol = 1e-5 + assert_allclose(filtered_real, filtered_cplx.real, rtol=rtol, atol=atol) + + +def test_butterworth_3D_zeros(): + im = np.zeros((3, 4, 5)) + filtered = butterworth(im) + assert filtered.shape == im.shape + assert_array_equal(im, filtered) + + +def test_butterworth_4D_zeros(): + im = np.zeros((3, 4, 5, 6)) + filtered = butterworth(im) + assert filtered.shape == im.shape + assert_array_equal(im, filtered) + + +@pytest.mark.parametrize( + "chan, dtype", + [(0, np.float64), (1, np.complex128), (2, np.uint8), (3, np.int64)], +) +def test_butterworth_4D_channel(chan, dtype): + im = np.zeros((3, 4, 5, 6), dtype=dtype) + filtered = butterworth(im, channel_axis=chan) + assert filtered.shape == im.shape + + +def test_butterworth_correctness_bw(): + small = coins()[180:190, 260:270] + filtered = butterworth(small, cutoff_frequency_ratio=0.2) + # fmt: off + correct = np.array( + [ + [ 28.63019362, -17.69023786, 26.95346957, 20.57423019, -15.1933463 , -28.05828136, -35.25135674, -25.70376951, -43.37121955, -16.87688457], + [ 4.62077869, 36.5726672 , 28.41926375, -22.86436829, -25.32375274, -19.94182623, -2.9666164 , 6.62250413, 3.55910886, -33.15358921], + [ 25.00377084, 34.2948942 , -15.13862785, -15.34354183, -12.68722526, 12.82729905, 5.21622357, 11.41087761, 16.33690526, -50.39790969], + [ 72.62331496, -14.7924709 , -22.14868895, -7.47854864, 9.66784721, 24.37625693, 12.5479457 , -1.38194367, 2.40079497, -26.61141413], + [ 21.85962078, -56.73932031, -14.82425429, 4.10524297, -19.16561768, -48.19021687, 5.0258744 , 28.82432166, 0.66992097, 9.8378842 ], + [-54.93417679, -5.12037233, 19.2956981 , 38.56431593, 27.95408908, -3.53103389, 23.75329532, -6.92615359, -8.50823024, 7.05743093], + [-30.51016624, -9.99691211, -7.1080672 , 23.67643315, 1.61919726, 12.94103905, -29.08141699, -11.56937511, 22.70988847, 32.04063285], + [ -7.51780937, -30.27899181, -2.57782655, -1.58947887, -2.13564576, -11.34039302, 1.59165041, 14.39173421, -14.15148821, -2.21664717], + [ 14.81167298, -3.75274782, 18.41459894, 15.80334075, -19.7477109 , -3.68619619, -2.9513036 , -10.17325791, 18.32438702, 18.68003971], + [-50.53430811, 12.14152989, 17.69341877, 9.1858496 , 12.1470914 , 1.45865179, 61.08961357, 29.76775029, -11.04603619, 24.18621404], + ] + ) + # fmt: on + assert_allclose(filtered, correct) + + +def test_butterworth_correctness_rgb(): + small = astronaut()[135:145, 205:215] + filtered = butterworth( + small, cutoff_frequency_ratio=0.3, high_pass=True, channel_axis=-1 + ) + correct = np.array( + [ + [ + [-5.30292781e-01, 2.17985072e00, 2.86622486e00], + [6.39360740e00, 9.30643715e00, 8.61226660e00], + [5.47978436e00, 1.03641402e01, 1.02940329e01], + [8.88312002e00, 7.29681652e00, 8.16021235e00], + [4.67693778e00, 6.33135145e-01, -2.51296407e00], + [3.21039522e00, -9.14893931e-01, -2.11543661e00], + [4.61985125e-02, -6.10682453e00, -1.72837650e00], + [-4.59492989e00, -7.35887525e00, -1.03532871e01], + [-3.67859542e00, -4.36371621e00, -5.67371459e00], + [-4.38264080e00, -6.08362280e00, -9.20394882e00], + ], + [ + [-2.46191390e00, -2.10996960e00, -1.41287606e00], + [4.87042304e-01, 4.70686760e-01, 2.90817746e00], + [9.33095004e-01, -2.11867564e-01, 3.10917925e00], + [-2.35660768e00, -1.35043153e00, -2.67062162e00], + [-1.22363424e00, 1.11155488e-01, 1.25392954e00], + [-1.05667680e00, 1.58195605e-01, 6.11873557e-01], + [-4.12128910e00, -3.55994486e00, -8.75303054e00], + [2.47171790e00, 2.70762582e00, 5.69543552e00], + [6.97042504e-01, -2.24173305e00, 3.26477871e-01], + [5.00195333e-01, -2.66024743e00, -1.87479563e00], + ], + [ + [-4.40136260e00, -4.02254309e00, -4.89246563e00], + [-4.64563864e00, -6.21442755e00, -9.31399553e00], + [-2.11532959e00, -2.58844609e00, -4.20629743e00], + [-3.40862389e00, -3.29511853e00, -4.78220207e00], + [-8.06768327e-01, -4.01651211e00, -2.84783939e00], + [1.72379068e00, 1.00930709e00, 2.57575911e00], + [-2.13771052e00, -1.75564076e00, -2.88676819e00], + [-2.72015191e-01, -1.61610409e-01, 2.15906305e00], + [-3.80356741e00, -7.30201675e-01, -3.79800352e00], + [1.43534281e-01, -2.95121861e00, -2.67070135e00], + ], + [ + [1.03480271e00, 6.34545011e00, 3.53610283e00], + [7.44740677e00, 9.97350707e00, 1.25152734e01], + [3.10493189e00, 5.15553793e00, 6.48354940e00], + [-7.89260096e-01, 3.04573015e-01, -1.43829810e00], + [-1.46298411e00, 1.23095495e00, -1.33983509e00], + [2.82986807e00, 2.80546223e00, 6.39492794e00], + [-9.15293187e-01, 2.88688464e00, -9.69417480e-01], + [4.50217964e00, 2.90410068e00, 5.39107589e00], + [-5.71608069e-01, 1.78198962e00, -3.72062011e-01], + [7.43870617e00, 8.78780364e00, 9.91142612e00], + ], + [ + [-1.01243616e01, -1.46725955e01, -1.63691866e01], + [1.06512445e01, 7.84699418e00, 1.05428678e01], + [4.75343829e00, 6.11329861e00, 2.81633365e00], + [7.78936796e00, 9.63684277e00, 1.21495065e01], + [5.19238043e00, 5.38165743e00, 8.03025884e00], + [1.67424214e00, 2.25530135e00, 2.44161390e-01], + [-3.18012002e-01, 1.99405335e00, -4.33960644e-01], + [-1.21700957e00, -2.65973900e00, -6.31515766e-01], + [-4.87805104e00, -5.55289609e00, -8.50052504e00], + [1.43493808e01, 1.77252074e01, 1.92810954e01], + ], + [ + [-4.21712178e01, -4.47409535e01, -4.16375264e01], + [1.18585381e00, 1.33732681e00, -1.45927283e00], + [-4.83275742e00, -7.14344851e00, -7.59812923e00], + [-7.13716513e00, -1.10025632e01, -1.16111397e01], + [-5.00275373e00, -4.20410732e00, -4.93030043e00], + [1.98421851e00, 2.68393141e00, 3.14898078e00], + [1.97471502e00, -2.11937555e00, 2.04674150e00], + [3.42916035e00, 4.98808524e00, 6.74436447e00], + [-3.29035900e-01, -9.88239773e-01, 2.38909382e-02], + [2.58646940e01, 2.40294324e01, 2.64535438e01], + ], + [ + [-2.72408341e01, -2.51637965e01, -2.95566971e01], + [4.83667855e00, 5.63749968e00, 6.97366639e00], + [6.18182884e00, 2.89519333e00, 6.15697112e00], + [-1.03326540e00, -4.04702873e00, -5.50872246e00], + [-6.92401355e00, -8.99374166e00, -9.43201766e00], + [-7.24967366e00, -1.16225741e01, -1.26385982e01], + [-7.79470220e00, -9.36143025e00, -7.13686778e00], + [-1.22393834e01, -1.24094588e01, -1.70498337e01], + [-4.65034860e00, -3.93071471e00, -4.65788605e00], + [2.47461715e01, 2.46389560e01, 3.11843915e01], + ], + [ + [1.22510987e00, -3.30423292e00, -1.02785428e01], + [-2.41285934e01, -1.60883211e01, -1.97064909e01], + [9.77242420e00, 1.80847757e01, 2.01088714e01], + [1.21335913e01, 1.16812821e01, 1.20531919e01], + [-1.64052514e00, -4.45404672e00, -3.83103216e00], + [9.97519545e-01, -6.32678881e00, -4.89843180e-01], + [1.07464325e01, 2.62880708e01, 1.74691665e01], + [2.31869805e00, 1.91935135e00, -9.65612833e-01], + [-9.23026361e00, -1.75138706e01, -1.39243019e01], + [4.60784836e00, 5.60845273e00, 5.28255564e00], + ], + [ + [9.68795318e00, 2.78851276e00, 5.45620353e00], + [-1.02076906e01, -1.47926224e01, -1.43257049e01], + [-2.17025353e00, 6.23446752e00, 5.21771748e00], + [1.57074742e01, 2.17163634e01, 2.55600809e01], + [7.03884578e00, 1.29273058e01, 7.50960315e00], + [-6.69896692e00, -1.83433042e01, -1.60702492e01], + [7.44877725e00, 1.28971365e01, 1.10234666e01], + [5.25663607e00, 9.80648891e00, 1.22955858e01], + [-7.44903684e00, -1.92670342e01, -1.68232131e01], + [1.25609220e01, 2.09808909e01, 2.21425299e01], + ], + [ + [2.87825597e00, 3.37945227e00, 3.05777360e00], + [1.18858884e00, -5.27430874e00, -6.96009863e00], + [-7.55910235e00, -2.12068126e01, -2.06925790e01], + [-1.47217788e01, -1.45626702e01, -1.56493571e01], + [-5.60886203e00, 8.81908697e-01, 5.47367282e00], + [-1.00478644e01, -8.01471176e00, -7.45670458e00], + [3.61521638e00, 8.99194959e00, 4.93826323e00], + [7.87025438e00, 1.34804191e01, 1.96899695e01], + [-5.50012037e00, -6.40490471e00, -1.17265188e01], + [6.17010624e00, 1.56199152e01, 1.79889524e01], + ], + ] + ) + assert_allclose(filtered, correct) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_gabor.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_gabor.py new file mode 100644 index 0000000000000000000000000000000000000000..40a5cb74a409fa1c7641801e9889ea506d9baaca --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_gabor.py @@ -0,0 +1,108 @@ +import numpy as np +import pytest +from numpy.testing import assert_almost_equal, assert_array_almost_equal, assert_equal + +from skimage._shared.utils import _supported_float_type +from skimage.filters._gabor import _sigma_prefactor, gabor, gabor_kernel + + +def test_gabor_kernel_size(): + sigma_x = 5 + sigma_y = 10 + # Sizes cut off at +/- three sigma + 1 for the center + size_x = sigma_x * 6 + 1 + size_y = sigma_y * 6 + 1 + + kernel = gabor_kernel(0, theta=0, sigma_x=sigma_x, sigma_y=sigma_y) + assert_equal(kernel.shape, (size_y, size_x)) + + kernel = gabor_kernel(0, theta=np.pi / 2, sigma_x=sigma_x, sigma_y=sigma_y) + assert_equal(kernel.shape, (size_x, size_y)) + + +def test_gabor_kernel_bandwidth(): + kernel = gabor_kernel(1, bandwidth=1) + assert_equal(kernel.shape, (5, 5)) + + kernel = gabor_kernel(1, bandwidth=0.5) + assert_equal(kernel.shape, (9, 9)) + + kernel = gabor_kernel(0.5, bandwidth=1) + assert_equal(kernel.shape, (9, 9)) + + +@pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) +def test_gabor_kernel_dtype(dtype): + kernel = gabor_kernel(1, bandwidth=1, dtype=dtype) + assert kernel.dtype == dtype + + +@pytest.mark.parametrize('dtype', [np.uint8, np.float32]) +def test_gabor_kernel_invalid_dtype(dtype): + with pytest.raises(ValueError): + kernel = gabor_kernel(1, bandwidth=1, dtype=dtype) + assert kernel.dtype == dtype + + +def test_sigma_prefactor(): + assert_almost_equal(_sigma_prefactor(1), 0.56, 2) + assert_almost_equal(_sigma_prefactor(0.5), 1.09, 2) + + +def test_gabor_kernel_sum(): + for sigma_x in range(1, 10, 2): + for sigma_y in range(1, 10, 2): + for frequency in range(0, 10, 2): + kernel = gabor_kernel( + frequency + 0.1, theta=0, sigma_x=sigma_x, sigma_y=sigma_y + ) + # make sure gaussian distribution is covered nearly 100% + assert_almost_equal(np.abs(kernel).sum(), 1, 2) + + +def test_gabor_kernel_theta(): + for sigma_x in range(1, 10, 2): + for sigma_y in range(1, 10, 2): + for frequency in range(0, 10, 2): + for theta in range(0, 10, 2): + kernel0 = gabor_kernel( + frequency + 0.1, theta=theta, sigma_x=sigma_x, sigma_y=sigma_y + ) + kernel180 = gabor_kernel( + frequency, theta=theta + np.pi, sigma_x=sigma_x, sigma_y=sigma_y + ) + + assert_array_almost_equal(np.abs(kernel0), np.abs(kernel180)) + + +def test_gabor(): + Y, X = np.mgrid[:40, :40] + frequencies = (0.1, 0.3) + wave_images = [np.sin(2 * np.pi * X * f) for f in frequencies] + + def match_score(image, frequency): + gabor_responses = gabor(image, frequency) + return np.mean(np.hypot(*gabor_responses)) + + # Gabor scores: diagonals are frequency-matched, off-diagonals are not. + responses = np.array( + [[match_score(image, f) for f in frequencies] for image in wave_images] + ) + assert responses[0, 0] > responses[0, 1] + assert responses[1, 1] > responses[0, 1] + assert responses[0, 0] > responses[1, 0] + assert responses[1, 1] > responses[1, 0] + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_gabor_float_dtype(dtype): + image = np.ones((16, 16), dtype=dtype) + y = gabor(image, 0.3) + assert all(arr.dtype == _supported_float_type(image.dtype) for arr in y) + + +@pytest.mark.parametrize('dtype', [np.uint8, np.int32, np.intp]) +def test_gabor_int_dtype(dtype): + image = np.full((16, 16), 128, dtype=dtype) + y = gabor(image, 0.3) + assert all(arr.dtype == dtype for arr in y) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_gaussian.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_gaussian.py new file mode 100644 index 0000000000000000000000000000000000000000..2f5a33b595b283612c519cc88b3dc91c16c9c545 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_gaussian.py @@ -0,0 +1,166 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from skimage._shared.utils import _supported_float_type +from skimage.filters import difference_of_gaussians, gaussian + + +def test_negative_sigma(): + a = np.zeros((3, 3)) + a[1, 1] = 1 + with pytest.raises(ValueError): + gaussian(a, sigma=-1.0) + with pytest.raises(ValueError): + gaussian(a, sigma=[-1.0, 1.0]) + with pytest.raises(ValueError): + gaussian(a, sigma=np.asarray([-1.0, 1.0])) + + +def test_null_sigma(): + a = np.zeros((3, 3)) + a[1, 1] = 1.0 + assert np.all(gaussian(a, sigma=0, preserve_range=True) == a) + + +def test_default_sigma(): + a = np.zeros((3, 3)) + a[1, 1] = 1.0 + assert_array_equal( + gaussian(a, preserve_range=True), gaussian(a, preserve_range=True, sigma=1) + ) + + +@pytest.mark.parametrize( + 'dtype', [np.uint8, np.int32, np.float16, np.float32, np.float64] +) +def test_image_dtype(dtype): + a = np.zeros((3, 3), dtype=dtype) + assert gaussian(a).dtype == _supported_float_type(a.dtype) + + +def test_energy_decrease(): + a = np.zeros((3, 3)) + a[1, 1] = 1.0 + gaussian_a = gaussian(a, preserve_range=True, sigma=1, mode='reflect') + assert gaussian_a.std() < a.std() + + +@pytest.mark.parametrize('channel_axis', [0, 1, -1]) +def test_multichannel(channel_axis): + a = np.zeros((5, 5, 3)) + a[1, 1] = np.arange(1, 4) + a = np.moveaxis(a, -1, channel_axis) + gaussian_rgb_a = gaussian( + a, sigma=1, mode='reflect', preserve_range=True, channel_axis=channel_axis + ) + # Check that the mean value is conserved in each channel + # (color channels are not mixed together) + spatial_axes = tuple([ax for ax in range(a.ndim) if ax != channel_axis % a.ndim]) + assert np.allclose( + a.mean(axis=spatial_axes), gaussian_rgb_a.mean(axis=spatial_axes) + ) + + if channel_axis % a.ndim == 2: + # Check that the mean value is conserved in each channel + # (color channels are not mixed together) + assert np.allclose( + a.mean(axis=spatial_axes), gaussian_rgb_a.mean(axis=spatial_axes) + ) + # Iterable sigma + gaussian_rgb_a = gaussian( + a, sigma=[1, 2], mode='reflect', channel_axis=channel_axis, preserve_range=True + ) + assert np.allclose( + a.mean(axis=spatial_axes), gaussian_rgb_a.mean(axis=spatial_axes) + ) + + +def test_preserve_range(): + """Test preserve_range parameter.""" + ones = np.ones((2, 2), dtype=np.int64) + filtered_ones = gaussian(ones, preserve_range=False) + assert np.all(filtered_ones == filtered_ones[0, 0]) + assert filtered_ones[0, 0] < 1e-10 + + filtered_preserved = gaussian(ones, preserve_range=True) + assert np.all(filtered_preserved == 1.0) + + img = np.array([[10.0, -10.0], [-4, 3]], dtype=np.float32) + gaussian(img, sigma=1) + + +def test_1d_ok(): + """Testing Gaussian Filter for 1D array. + With any array consisting of positive integers and only one zero - it + should filter all values to be greater than 0.1 + """ + nums = np.arange(7) + filtered = gaussian(nums, preserve_range=True) + assert np.all(filtered > 0.1) + + +def test_4d_ok(): + img = np.zeros((5,) * 4) + img[2, 2, 2, 2] = 1 + res = gaussian(img, sigma=1, mode='reflect', preserve_range=True) + assert np.allclose(res.sum(), 1) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_preserve_output(dtype): + image = np.arange(9, dtype=dtype).reshape((3, 3)) + out = np.zeros_like(image, dtype=dtype) + gaussian_image = gaussian(image, sigma=1, out=out, preserve_range=True) + assert gaussian_image is out + + +def test_output_error(): + image = np.arange(9, dtype=np.float32).reshape((3, 3)) + out = np.zeros_like(image, dtype=np.uint8) + with pytest.raises(ValueError, match="dtype of `out` must be float"): + gaussian(image, sigma=1, out=out, preserve_range=True) + + +@pytest.mark.parametrize("s", [1, (2, 3)]) +@pytest.mark.parametrize("s2", [4, (5, 6)]) +@pytest.mark.parametrize("channel_axis", [None, 0, 1, -1]) +def test_difference_of_gaussians(s, s2, channel_axis): + image = np.random.rand(10, 10) + if channel_axis is not None: + n_channels = 5 + image = np.stack((image,) * n_channels, channel_axis) + im1 = gaussian(image, sigma=s, preserve_range=True, channel_axis=channel_axis) + im2 = gaussian(image, sigma=s2, preserve_range=True, channel_axis=channel_axis) + dog = im1 - im2 + dog2 = difference_of_gaussians(image, s, s2, channel_axis=channel_axis) + assert np.allclose(dog, dog2) + + +@pytest.mark.parametrize("s", [1, (1, 2)]) +def test_auto_sigma2(s): + image = np.random.rand(10, 10) + im1 = gaussian(image, sigma=s, preserve_range=True) + s2 = 1.6 * np.array(s) + im2 = gaussian(image, sigma=s2, preserve_range=True) + dog = im1 - im2 + dog2 = difference_of_gaussians(image, s, s2) + assert np.allclose(dog, dog2) + + +def test_dog_invalid_sigma_dims(): + image = np.ones((5, 5, 3)) + with pytest.raises(ValueError): + difference_of_gaussians(image, (1, 2)) + with pytest.raises(ValueError): + difference_of_gaussians(image, 1, (3, 4)) + with pytest.raises(ValueError): + difference_of_gaussians(image, (1, 2, 3), channel_axis=-1) + + +def test_dog_invalid_sigma2(): + image = np.ones((3, 3)) + with pytest.raises(ValueError): + difference_of_gaussians(image, 3, 2) + with pytest.raises(ValueError): + difference_of_gaussians(image, (1, 5), (2, 4)) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_lpi_filter.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_lpi_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..23b7ea2c1472766c9e9e2c6edc1d6c1bec99d140 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_lpi_filter.py @@ -0,0 +1,97 @@ +import numpy as np +import pytest +from numpy.testing import assert_, assert_equal, assert_array_almost_equal + +from skimage._shared.utils import _supported_float_type +from skimage.data import camera, coins +from skimage.filters import ( + LPIFilter2D, + filter_inverse, + filter_forward, + wiener, + gaussian, +) + + +def test_filter_forward(): + def filt_func(r, c, sigma=2): + return (1 / (2 * np.pi * sigma**2)) * np.exp(-(r**2 + c**2) / (2 * sigma**2)) + + gaussian_args = { + 'sigma': 2, + 'preserve_range': True, + 'mode': 'constant', + 'truncate': 20, # LPI filtering is more precise than the truncated + # Gaussian, so don't truncate at the default of 4 sigma + } + + # Odd image size + image = coins()[:303, :383] + filtered = filter_forward(image, filt_func) + filtered_gaussian = gaussian(image, **gaussian_args) + assert_array_almost_equal(filtered, filtered_gaussian) + + # Even image size + image = coins() + filtered = filter_forward(image, filt_func) + filtered_gaussian = gaussian(image, **gaussian_args) + assert_array_almost_equal(filtered, filtered_gaussian) + + +class TestLPIFilter2D: + img = camera()[:50, :50] + + def filt_func(self, r, c): + return np.exp(-(r**2 + c**2) / 1) + + def setup_method(self): + self.f = LPIFilter2D(self.filt_func) + + @pytest.mark.parametrize('c_slice', [slice(None), slice(0, -5), slice(0, -20)]) + def test_ip_shape(self, c_slice): + x = self.img[:, c_slice] + assert_equal(self.f(x).shape, x.shape) + + @pytest.mark.parametrize('dtype', [np.uint8, np.float16, np.float32, np.float64]) + def test_filter_inverse(self, dtype): + img = self.img.astype(dtype, copy=False) + expected_dtype = _supported_float_type(dtype) + + F = self.f(img) + assert F.dtype == expected_dtype + + g = filter_inverse(F, predefined_filter=self.f) + assert g.dtype == expected_dtype + assert_equal(g.shape, self.img.shape) + + g1 = filter_inverse(F[::-1, ::-1], predefined_filter=self.f) + assert_((g - g1[::-1, ::-1]).sum() < 55) + + # test cache + g1 = filter_inverse(F[::-1, ::-1], predefined_filter=self.f) + assert_((g - g1[::-1, ::-1]).sum() < 55) + + g1 = filter_inverse(F[::-1, ::-1], self.filt_func) + assert_((g - g1[::-1, ::-1]).sum() < 55) + + @pytest.mark.parametrize('dtype', [np.uint8, np.float16, np.float32, np.float64]) + def test_wiener(self, dtype): + img = self.img.astype(dtype, copy=False) + expected_dtype = _supported_float_type(dtype) + + F = self.f(img) + assert F.dtype == expected_dtype + + g = wiener(F, predefined_filter=self.f) + assert g.dtype == expected_dtype + assert_equal(g.shape, self.img.shape) + + g1 = wiener(F[::-1, ::-1], predefined_filter=self.f) + assert_((g - g1[::-1, ::-1]).sum() < 1) + + g1 = wiener(F[::-1, ::-1], self.filt_func) + assert_((g - g1[::-1, ::-1]).sum() < 1) + + def test_non_callable(self): + with pytest.raises(ValueError): + LPIFilter2D(None) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_median.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_median.py new file mode 100644 index 0000000000000000000000000000000000000000..c29c3bb50eb921b5e58ffa3844eaf7f8cb866089 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_median.py @@ -0,0 +1,74 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy import ndimage + +from skimage.filters import median, rank +from skimage._shared.testing import assert_stacklevel + + +@pytest.fixture +def image(): + return np.array( + [ + [1, 2, 3, 2, 1], + [1, 1, 2, 2, 3], + [3, 2, 1, 2, 1], + [3, 2, 1, 1, 1], + [1, 2, 1, 2, 3], + ], + dtype=np.uint8, + ) + + +@pytest.mark.parametrize( + "mode, cval, behavior, warning_type", + [ + ('nearest', 0.0, 'ndimage', None), + ('constant', 0.0, 'rank', UserWarning), + ('nearest', 0.0, 'rank', None), + ('nearest', 0.0, 'ndimage', None), + ], +) +def test_median_warning(image, mode, cval, behavior, warning_type): + if warning_type: + with pytest.warns(warning_type) as record: + median(image, mode=mode, behavior=behavior) + assert_stacklevel(record) + else: + median(image, mode=mode, behavior=behavior) + + +@pytest.mark.parametrize( + "behavior, func, params", + [ + ('ndimage', ndimage.median_filter, {'size': (3, 3)}), + ('rank', rank.median, {'footprint': np.ones((3, 3), dtype=np.uint8)}), + ], +) +def test_median_behavior(image, behavior, func, params): + assert_allclose(median(image, behavior=behavior), func(image, **params)) + + +@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.float32, np.float64]) +def test_median_preserve_dtype(image, dtype): + median_image = median(image.astype(dtype), behavior='ndimage') + assert median_image.dtype == dtype + + +def test_median_error_ndim(): + img = np.random.randint(0, 10, size=(5, 5, 5, 5), dtype=np.uint8) + with pytest.raises(ValueError): + median(img, behavior='rank') + + +@pytest.mark.parametrize( + "img, behavior", + [ + (np.random.randint(0, 10, size=(3, 3), dtype=np.uint8), 'rank'), + (np.random.randint(0, 10, size=(3, 3), dtype=np.uint8), 'ndimage'), + (np.random.randint(0, 10, size=(3, 3, 3), dtype=np.uint8), 'ndimage'), + ], +) +def test_median(img, behavior): + median(img, behavior=behavior) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_ridges.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_ridges.py new file mode 100644 index 0000000000000000000000000000000000000000..4c2482c01f571850f98a674a0b448aa75079d18b --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_ridges.py @@ -0,0 +1,292 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_less, assert_equal + +from skimage import img_as_float +from skimage._shared.utils import _supported_float_type +from skimage.color import rgb2gray +from skimage.data import camera, retina +from skimage.filters import frangi, hessian, meijering, sato +from skimage.util import crop, invert + + +def test_2d_null_matrix(): + a_black = np.zeros((3, 3)).astype(np.uint8) + a_white = invert(a_black) + + zeros = np.zeros((3, 3)) + ones = np.ones((3, 3)) + + assert_equal(meijering(a_black, black_ridges=True), zeros) + assert_equal(meijering(a_white, black_ridges=False), zeros) + + assert_equal(sato(a_black, black_ridges=True, mode='reflect'), zeros) + assert_equal(sato(a_white, black_ridges=False, mode='reflect'), zeros) + + assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) + assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) + + assert_equal(hessian(a_black, black_ridges=False, mode='reflect'), ones) + assert_equal(hessian(a_white, black_ridges=True, mode='reflect'), ones) + + +def test_3d_null_matrix(): + # Note: last axis intentionally not size 3 to avoid 2D+RGB autodetection + # warning from an internal call to `skimage.filters.gaussian`. + a_black = np.zeros((3, 3, 5)).astype(np.uint8) + a_white = invert(a_black) + + zeros = np.zeros((3, 3, 5)) + ones = np.ones((3, 3, 5)) + + assert_allclose(meijering(a_black, black_ridges=True), zeros, atol=1e-1) + assert_allclose(meijering(a_white, black_ridges=False), zeros, atol=1e-1) + + assert_equal(sato(a_black, black_ridges=True, mode='reflect'), zeros) + assert_equal(sato(a_white, black_ridges=False, mode='reflect'), zeros) + + assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) + assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) + + assert_equal(hessian(a_black, black_ridges=False, mode='reflect'), ones) + assert_equal(hessian(a_white, black_ridges=True, mode='reflect'), ones) + + +def test_2d_energy_decrease(): + a_black = np.zeros((5, 5)).astype(np.uint8) + a_black[2, 2] = 255 + a_white = invert(a_black) + + assert_array_less(meijering(a_black, black_ridges=True).std(), a_black.std()) + assert_array_less(meijering(a_white, black_ridges=False).std(), a_white.std()) + + assert_array_less( + sato(a_black, black_ridges=True, mode='reflect').std(), a_black.std() + ) + assert_array_less( + sato(a_white, black_ridges=False, mode='reflect').std(), a_white.std() + ) + + assert_array_less(frangi(a_black, black_ridges=True).std(), a_black.std()) + assert_array_less(frangi(a_white, black_ridges=False).std(), a_white.std()) + + assert_array_less( + hessian(a_black, black_ridges=True, mode='reflect').std(), a_black.std() + ) + assert_array_less( + hessian(a_white, black_ridges=False, mode='reflect').std(), a_white.std() + ) + + +def test_3d_energy_decrease(): + a_black = np.zeros((5, 5, 5)).astype(np.uint8) + a_black[2, 2, 2] = 255 + a_white = invert(a_black) + + assert_array_less(meijering(a_black, black_ridges=True).std(), a_black.std()) + assert_array_less(meijering(a_white, black_ridges=False).std(), a_white.std()) + + assert_array_less( + sato(a_black, black_ridges=True, mode='reflect').std(), a_black.std() + ) + assert_array_less( + sato(a_white, black_ridges=False, mode='reflect').std(), a_white.std() + ) + + assert_array_less(frangi(a_black, black_ridges=True).std(), a_black.std()) + assert_array_less(frangi(a_white, black_ridges=False).std(), a_white.std()) + + assert_array_less( + hessian(a_black, black_ridges=True, mode='reflect').std(), a_black.std() + ) + assert_array_less( + hessian(a_white, black_ridges=False, mode='reflect').std(), a_white.std() + ) + + +def test_2d_linearity(): + a_black = np.ones((3, 3)).astype(np.uint8) + a_white = invert(a_black) + + assert_allclose( + meijering(1 * a_black, black_ridges=True), + meijering(10 * a_black, black_ridges=True), + atol=1e-3, + ) + assert_allclose( + meijering(1 * a_white, black_ridges=False), + meijering(10 * a_white, black_ridges=False), + atol=1e-3, + ) + + assert_allclose( + sato(1 * a_black, black_ridges=True, mode='reflect'), + sato(10 * a_black, black_ridges=True, mode='reflect'), + atol=1e-3, + ) + assert_allclose( + sato(1 * a_white, black_ridges=False, mode='reflect'), + sato(10 * a_white, black_ridges=False, mode='reflect'), + atol=1e-3, + ) + + assert_allclose( + frangi(1 * a_black, black_ridges=True), + frangi(10 * a_black, black_ridges=True), + atol=1e-3, + ) + assert_allclose( + frangi(1 * a_white, black_ridges=False), + frangi(10 * a_white, black_ridges=False), + atol=1e-3, + ) + + assert_allclose( + hessian(1 * a_black, black_ridges=True, mode='reflect'), + hessian(10 * a_black, black_ridges=True, mode='reflect'), + atol=1e-3, + ) + assert_allclose( + hessian(1 * a_white, black_ridges=False, mode='reflect'), + hessian(10 * a_white, black_ridges=False, mode='reflect'), + atol=1e-3, + ) + + +def test_3d_linearity(): + # Note: last axis intentionally not size 3 to avoid 2D+RGB autodetection + # warning from an internal call to `skimage.filters.gaussian`. + a_black = np.ones((3, 3, 5)).astype(np.uint8) + a_white = invert(a_black) + + assert_allclose( + meijering(1 * a_black, black_ridges=True), + meijering(10 * a_black, black_ridges=True), + atol=1e-3, + ) + assert_allclose( + meijering(1 * a_white, black_ridges=False), + meijering(10 * a_white, black_ridges=False), + atol=1e-3, + ) + + assert_allclose( + sato(1 * a_black, black_ridges=True, mode='reflect'), + sato(10 * a_black, black_ridges=True, mode='reflect'), + atol=1e-3, + ) + assert_allclose( + sato(1 * a_white, black_ridges=False, mode='reflect'), + sato(10 * a_white, black_ridges=False, mode='reflect'), + atol=1e-3, + ) + + assert_allclose( + frangi(1 * a_black, black_ridges=True), + frangi(10 * a_black, black_ridges=True), + atol=1e-3, + ) + assert_allclose( + frangi(1 * a_white, black_ridges=False), + frangi(10 * a_white, black_ridges=False), + atol=1e-3, + ) + + assert_allclose( + hessian(1 * a_black, black_ridges=True, mode='reflect'), + hessian(10 * a_black, black_ridges=True, mode='reflect'), + atol=1e-3, + ) + assert_allclose( + hessian(1 * a_white, black_ridges=False, mode='reflect'), + hessian(10 * a_white, black_ridges=False, mode='reflect'), + atol=1e-3, + ) + + +def test_2d_cropped_camera_image(): + a_black = crop(camera(), ((200, 212), (100, 312))) + a_white = invert(a_black) + + np.zeros((100, 100)) + ones = np.ones((100, 100)) + + assert_allclose( + meijering(a_black, black_ridges=True), meijering(a_white, black_ridges=False) + ) + + assert_allclose( + sato(a_black, black_ridges=True, mode='reflect'), + sato(a_white, black_ridges=False, mode='reflect'), + ) + + assert_allclose( + frangi(a_black, black_ridges=True), frangi(a_white, black_ridges=False) + ) + + assert_allclose( + hessian(a_black, black_ridges=True, mode='reflect'), ones, atol=1 - 1e-7 + ) + assert_allclose( + hessian(a_white, black_ridges=False, mode='reflect'), ones, atol=1 - 1e-7 + ) + + +@pytest.mark.parametrize('func', [meijering, sato, frangi, hessian]) +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_ridge_output_dtype(func, dtype): + img = img_as_float(camera()).astype(dtype, copy=False) + assert func(img).dtype == _supported_float_type(img.dtype) + + +def test_3d_cropped_camera_image(): + a_black = crop(camera(), ((200, 212), (100, 312))) + a_black = np.stack([a_black] * 5, axis=-1) + a_white = invert(a_black) + + np.zeros(a_black.shape) + ones = np.ones(a_black.shape) + + assert_allclose( + meijering(a_black, black_ridges=True), meijering(a_white, black_ridges=False) + ) + + assert_allclose( + sato(a_black, black_ridges=True, mode='reflect'), + sato(a_white, black_ridges=False, mode='reflect'), + ) + + assert_allclose( + frangi(a_black, black_ridges=True), frangi(a_white, black_ridges=False) + ) + + assert_allclose( + hessian(a_black, black_ridges=True, mode='reflect'), ones, atol=1 - 1e-7 + ) + assert_allclose( + hessian(a_white, black_ridges=False, mode='reflect'), ones, atol=1 - 1e-7 + ) + + +@pytest.mark.parametrize( + 'func, tol', [(frangi, 1e-2), (meijering, 1e-2), (sato, 2e-3), (hessian, 2e-2)] +) +def test_border_management(func, tol): + img = rgb2gray(retina()[300:500, 700:900]) + out = func(img, sigmas=[1], mode='reflect') + + full_std = out.std() + full_mean = out.mean() + inside_std = out[4:-4, 4:-4].std() + inside_mean = out[4:-4, 4:-4].mean() + border_std = np.stack([out[:4, :], out[-4:, :], out[:, :4].T, out[:, -4:].T]).std() + border_mean = np.stack( + [out[:4, :], out[-4:, :], out[:, :4].T, out[:, -4:].T] + ).mean() + + assert abs(full_std - inside_std) < tol + assert abs(full_std - border_std) < tol + assert abs(inside_std - border_std) < tol + assert abs(full_mean - inside_mean) < tol + assert abs(full_mean - border_mean) < tol + assert abs(inside_mean - border_mean) < tol diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_thresholding.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_thresholding.py new file mode 100644 index 0000000000000000000000000000000000000000..78876036223e6119f086f99282d399554ee6fb32 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_thresholding.py @@ -0,0 +1,823 @@ +import math + +import numpy as np +import pytest +from numpy.testing import ( + assert_allclose, + assert_almost_equal, + assert_array_equal, + assert_equal, +) +from scipy import ndimage as ndi + +from skimage import data, util +from skimage._shared._dependency_checks import has_mpl +from skimage._shared._warnings import expected_warnings +from skimage._shared.utils import _supported_float_type +from skimage.color import rgb2gray +from skimage.draw import disk +from skimage.exposure import histogram +from skimage.filters._multiotsu import ( + _get_multiotsu_thresh_indices, + _get_multiotsu_thresh_indices_lut, +) +from skimage.filters.thresholding import ( + _cross_entropy, + _mean_std, + threshold_isodata, + threshold_li, + threshold_local, + threshold_mean, + threshold_minimum, + threshold_multiotsu, + threshold_niblack, + threshold_otsu, + threshold_sauvola, + threshold_triangle, + threshold_yen, + try_all_threshold, +) + + +class TestSimpleImage: + def setup_method(self): + self.image = np.array( + [ + [0, 0, 1, 3, 5], + [0, 1, 4, 3, 4], + [1, 2, 5, 4, 1], + [2, 4, 5, 2, 1], + [4, 5, 1, 0, 0], + ], + dtype=int, + ) + + def test_minimum(self): + with pytest.raises(RuntimeError): + threshold_minimum(self.image) + + @pytest.mark.skipif(not has_mpl, reason="matplotlib not installed") + def test_try_all_threshold(self): + fig, ax = try_all_threshold(self.image) + all_texts = [axis.texts for axis in ax if axis.texts != []] + text_content = [text.get_text() for x in all_texts for text in x] + assert 'RuntimeError' in text_content + + def test_otsu(self): + assert threshold_otsu(self.image) == 2 + + def test_otsu_negative_int(self): + image = self.image - 2 + assert threshold_otsu(image) == 0 + + def test_otsu_float_image(self): + image = np.float64(self.image) + assert 2 <= threshold_otsu(image) < 3 + + def test_li(self): + assert 2 < threshold_li(self.image) < 3 + + def test_li_negative_int(self): + image = self.image - 2 + assert 0 < threshold_li(image) < 1 + + def test_li_float_image(self): + image = self.image.astype(float) + assert 2 < threshold_li(image) < 3 + + def test_li_constant_image(self): + assert threshold_li(np.ones((10, 10))) == 1.0 + + def test_yen(self): + assert threshold_yen(self.image) == 2 + + def test_yen_negative_int(self): + image = self.image - 2 + assert threshold_yen(image) == 0 + + def test_yen_float_image(self): + image = np.float64(self.image) + assert 2 <= threshold_yen(image) < 3 + + def test_yen_arange(self): + image = np.arange(256) + assert threshold_yen(image) == 127 + + def test_yen_binary(self): + image = np.zeros([2, 256], dtype=np.uint8) + image[0] = 255 + assert threshold_yen(image) < 1 + + def test_yen_blank_zero(self): + image = np.zeros((5, 5), dtype=np.uint8) + assert threshold_yen(image) == 0 + + def test_yen_blank_max(self): + image = np.empty((5, 5), dtype=np.uint8) + image.fill(255) + assert threshold_yen(image) == 255 + + def test_isodata(self): + assert threshold_isodata(self.image) == 2 + assert threshold_isodata(self.image, return_all=True) == [2] + + def test_isodata_blank_zero(self): + image = np.zeros((5, 5), dtype=np.uint8) + assert threshold_isodata(image) == 0 + assert threshold_isodata(image, return_all=True) == [0] + + def test_isodata_linspace(self): + image = np.linspace(-127, 0, 256) + assert -63.8 < threshold_isodata(image) < -63.6 + assert_almost_equal( + threshold_isodata(image, return_all=True), [-63.74804688, -63.25195312] + ) + + def test_isodata_16bit(self): + np.random.seed(0) + imfloat = np.random.rand(256, 256) + assert 0.49 < threshold_isodata(imfloat, nbins=1024) < 0.51 + assert all(0.49 < threshold_isodata(imfloat, nbins=1024, return_all=True)) + + @pytest.mark.parametrize('ndim', [2, 3]) + def test_threshold_local_gaussian(self, ndim): + ref = np.array( + [ + [False, False, False, False, True], + [False, False, True, False, True], + [False, False, True, True, False], + [False, True, True, False, False], + [True, True, False, False, False], + ] + ) + if ndim == 2: + image = self.image + block_sizes = [3, (3,) * image.ndim] + else: + image = np.stack((self.image,) * 5, axis=-1) + ref = np.stack((ref,) * 5, axis=-1) + block_sizes = [3, (3,) * image.ndim, (3,) * (image.ndim - 1) + (1,)] + + for block_size in block_sizes: + out = threshold_local(image, block_size, method='gaussian', mode='reflect') + assert_equal(ref, image > out) + + out = threshold_local(image, 3, method='gaussian', mode='reflect', param=1 / 3) + assert_equal(ref, image > out) + + @pytest.mark.parametrize('ndim', [2, 3]) + def test_threshold_local_mean(self, ndim): + ref = np.array( + [ + [False, False, False, False, True], + [False, False, True, False, True], + [False, False, True, True, False], + [False, True, True, False, False], + [True, True, False, False, False], + ] + ) + if ndim == 2: + image = self.image + block_sizes = [3, (3,) * image.ndim] + else: + image = np.stack((self.image,) * 5, axis=-1) + ref = np.stack((ref,) * 5, axis=-1) + # Given the same data at each z location, the following block sizes + # will all give an equivalent result. + block_sizes = [3, (3,) * image.ndim, (3,) * (image.ndim - 1) + (1,)] + for block_size in block_sizes: + out = threshold_local(image, block_size, method='mean', mode='reflect') + assert_equal(ref, image > out) + + @pytest.mark.parametrize('block_size', [(3,), (3, 3, 3)]) + def test_threshold_local_invalid_block_size(self, block_size): + # len(block_size) != image.ndim + with pytest.raises(ValueError): + threshold_local(self.image, block_size, method='mean') + + @pytest.mark.parametrize('ndim', [2, 3]) + def test_threshold_local_median(self, ndim): + ref = np.array( + [ + [False, False, False, False, True], + [False, False, True, False, False], + [False, False, True, False, False], + [False, False, True, True, False], + [False, True, False, False, False], + ] + ) + if ndim == 2: + image = self.image + else: + image = np.stack((self.image,) * 5, axis=-1) + ref = np.stack((ref,) * 5, axis=-1) + out = threshold_local(image, 3, method='median', mode='reflect') + assert_equal(ref, image > out) + + def test_threshold_local_median_constant_mode(self): + out = threshold_local(self.image, 3, method='median', mode='constant', cval=20) + expected = np.array( + [ + [20.0, 1.0, 3.0, 4.0, 20.0], + [1.0, 1.0, 3.0, 4.0, 4.0], + [2.0, 2.0, 4.0, 4.0, 4.0], + [4.0, 4.0, 4.0, 1.0, 2.0], + [20.0, 5.0, 5.0, 2.0, 20.0], + ] + ) + assert_equal(expected, out) + + def test_threshold_niblack(self): + ref = np.array( + [ + [False, False, False, True, True], + [False, True, True, True, True], + [False, True, True, True, False], + [False, True, True, True, True], + [True, True, False, False, False], + ] + ) + thres = threshold_niblack(self.image, window_size=3, k=0.5) + out = self.image > thres + assert_equal(ref, out) + + def test_threshold_sauvola(self): + ref = np.array( + [ + [False, False, False, True, True], + [False, False, True, True, True], + [False, False, True, True, False], + [False, True, True, True, False], + [True, True, False, False, False], + ] + ) + thres = threshold_sauvola(self.image, window_size=3, k=0.2, r=128) + out = self.image > thres + assert_equal(ref, out) + + def test_threshold_niblack_iterable_window_size(self): + ref = np.array( + [ + [False, False, False, True, True], + [False, False, True, True, True], + [False, True, True, True, False], + [False, True, True, True, False], + [True, True, False, False, False], + ] + ) + thres = threshold_niblack(self.image, window_size=[3, 5], k=0.5) + out = self.image > thres + assert_array_equal(ref, out) + + def test_threshold_sauvola_iterable_window_size(self): + ref = np.array( + [ + [False, False, False, True, True], + [False, False, True, True, True], + [False, False, True, True, False], + [False, True, True, True, False], + [True, True, False, False, False], + ] + ) + thres = threshold_sauvola(self.image, window_size=(3, 5), k=0.2, r=128) + out = self.image > thres + assert_array_equal(ref, out) + + +def test_otsu_camera_image(): + camera = util.img_as_ubyte(data.camera()) + assert 101 < threshold_otsu(camera) < 103 + + +def test_otsu_camera_image_histogram(): + camera = util.img_as_ubyte(data.camera()) + hist = histogram(camera.ravel(), 256, source_range='image') + assert 101 < threshold_otsu(hist=hist) < 103 + + +def test_otsu_camera_image_counts(): + camera = util.img_as_ubyte(data.camera()) + counts, bin_centers = histogram(camera.ravel(), 256, source_range='image') + assert 101 < threshold_otsu(hist=counts) < 103 + + +def test_otsu_zero_count_histogram(): + """Issue #5497. + + As the histogram returned by np.bincount starts with zero, + it resulted in NaN-related issues. + """ + x = np.array([1, 2]) + + t1 = threshold_otsu(x) + t2 = threshold_otsu(hist=np.bincount(x)) + assert t1 == t2 + + +def test_otsu_coins_image(): + coins = util.img_as_ubyte(data.coins()) + assert 106 < threshold_otsu(coins) < 108 + + +def test_otsu_coins_image_as_float(): + coins = util.img_as_float(data.coins()) + assert 0.41 < threshold_otsu(coins) < 0.42 + + +def test_otsu_astro_image(): + img = util.img_as_ubyte(data.astronaut()) + with expected_warnings(['grayscale']): + assert 109 < threshold_otsu(img) < 111 + + +def test_otsu_one_color_image(): + img = np.ones((10, 10), dtype=np.uint8) + assert threshold_otsu(img) == 1 + + +def test_otsu_one_color_image_3d(): + img = np.ones((10, 10, 10), dtype=np.uint8) + assert threshold_otsu(img) == 1 + + +def test_li_camera_image(): + image = util.img_as_ubyte(data.camera()) + threshold = threshold_li(image) + ce_actual = _cross_entropy(image, threshold) + assert 78 < threshold_li(image) < 79 + assert ce_actual < _cross_entropy(image, threshold + 1) + assert ce_actual < _cross_entropy(image, threshold - 1) + + +def test_li_coins_image(): + image = util.img_as_ubyte(data.coins()) + threshold = threshold_li(image) + ce_actual = _cross_entropy(image, threshold) + assert 94 < threshold_li(image) < 95 + assert ce_actual < _cross_entropy(image, threshold + 1) + # in the case of the coins image, the minimum cross-entropy is achieved one + # threshold below that found by the iterative method. Not sure why that is + # but `threshold_li` does find the stationary point of the function (ie the + # tolerance can be reduced arbitrarily but the exact same threshold is + # found), so my guess is some kind of histogram binning effect. + assert ce_actual < _cross_entropy(image, threshold - 2) + + +def test_li_coins_image_as_float(): + coins = util.img_as_float(data.coins()) + assert 94 / 255 < threshold_li(coins) < 95 / 255 + + +def test_li_astro_image(): + image = util.img_as_ubyte(data.astronaut()) + threshold = threshold_li(image) + ce_actual = _cross_entropy(image, threshold) + assert 64 < threshold < 65 + assert ce_actual < _cross_entropy(image, threshold + 1) + assert ce_actual < _cross_entropy(image, threshold - 1) + + +def test_li_nan_image(): + image = np.full((5, 5), np.nan) + assert np.isnan(threshold_li(image)) + + +def test_li_inf_image(): + image = np.array([np.inf, np.nan]) + assert threshold_li(image) == np.inf + + +def test_li_inf_minus_inf(): + image = np.array([np.inf, -np.inf]) + assert threshold_li(image) == 0 + + +def test_li_constant_image_with_nan(): + image = np.array([8, 8, 8, 8, np.nan]) + assert threshold_li(image) == 8 + + +def test_li_arbitrary_start_point(): + cell = data.cell() + max_stationary_point = threshold_li(cell) + low_stationary_point = threshold_li(cell, initial_guess=np.percentile(cell, 5)) + optimum = threshold_li(cell, initial_guess=np.percentile(cell, 95)) + assert 67 < max_stationary_point < 68 + assert 48 < low_stationary_point < 49 + assert 111 < optimum < 112 + + +def test_li_negative_inital_guess(): + coins = data.coins() + with pytest.raises(ValueError, match=".*initial guess.*must be within the range"): + threshold_li(coins, initial_guess=-5) + + +@pytest.mark.parametrize( + "image", + [ + # See https://github.com/scikit-image/scikit-image/issues/4140 + [0, 0, 1, 0, 0, 1, 0, 1], + [0, 0, 0.1, 0, 0, 0.1, 0, 0.1], + [0, 0, 0.1, 0, 0, 0.1, 0.01, 0.1], + [0, 0, 1, 0, 0, 1, 0.5, 1], + [1, 1], + [1, 2], + # See https://github.com/scikit-image/scikit-image/issues/6744 + [0, 254, 255], + [0, 1, 255], + [0.1, 0.8, 0.9], + ], +) +def test_li_pathological(image): + image = np.array(image) + threshold = threshold_li(image) + assert np.isfinite(threshold) + + +def test_yen_camera_image(): + camera = util.img_as_ubyte(data.camera()) + assert 145 < threshold_yen(camera) < 147 + + +def test_yen_camera_image_histogram(): + camera = util.img_as_ubyte(data.camera()) + hist = histogram(camera.ravel(), 256, source_range='image') + assert 145 < threshold_yen(hist=hist) < 147 + + +def test_yen_camera_image_counts(): + camera = util.img_as_ubyte(data.camera()) + counts, bin_centers = histogram(camera.ravel(), 256, source_range='image') + assert 145 < threshold_yen(hist=counts) < 147 + + +def test_yen_coins_image(): + coins = util.img_as_ubyte(data.coins()) + assert 109 < threshold_yen(coins) < 111 + + +def test_yen_coins_image_as_float(): + coins = util.img_as_float(data.coins()) + assert 0.43 < threshold_yen(coins) < 0.44 + + +def test_local_even_block_size_error(): + img = data.camera() + with pytest.raises(ValueError): + threshold_local(img, block_size=4) + + +def test_isodata_camera_image(): + camera = util.img_as_ubyte(data.camera()) + + threshold = threshold_isodata(camera) + assert ( + np.floor( + (camera[camera <= threshold].mean() + camera[camera > threshold].mean()) + / 2.0 + ) + == threshold + ) + assert threshold == 102 + + assert (threshold_isodata(camera, return_all=True) == [102, 103]).all() + + +def test_isodata_camera_image_histogram(): + camera = util.img_as_ubyte(data.camera()) + hist = histogram(camera.ravel(), 256, source_range='image') + threshold = threshold_isodata(hist=hist) + assert threshold == 102 + + +def test_isodata_camera_image_counts(): + camera = util.img_as_ubyte(data.camera()) + counts, bin_centers = histogram(camera.ravel(), 256, source_range='image') + threshold = threshold_isodata(hist=counts) + assert threshold == 102 + + +def test_isodata_coins_image(): + coins = util.img_as_ubyte(data.coins()) + + threshold = threshold_isodata(coins) + assert ( + np.floor( + (coins[coins <= threshold].mean() + coins[coins > threshold].mean()) / 2.0 + ) + == threshold + ) + assert threshold == 107 + + assert threshold_isodata(coins, return_all=True) == [107] + + +def test_isodata_moon_image(): + moon = util.img_as_ubyte(data.moon()) + + threshold = threshold_isodata(moon) + assert ( + np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) + == threshold + ) + assert threshold == 86 + + thresholds = threshold_isodata(moon, return_all=True) + for threshold in thresholds: + assert ( + np.floor( + (moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0 + ) + == threshold + ) + assert_equal(thresholds, [86, 87, 88, 122, 123, 124, 139, 140]) + + +def test_isodata_moon_image_negative_int(): + moon = util.img_as_ubyte(data.moon()).astype(np.int32) + moon -= 100 + + threshold = threshold_isodata(moon) + assert ( + np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) + == threshold + ) + assert threshold == -14 + + thresholds = threshold_isodata(moon, return_all=True) + for threshold in thresholds: + assert ( + np.floor( + (moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0 + ) + == threshold + ) + assert_equal(thresholds, [-14, -13, -12, 22, 23, 24, 39, 40]) + + +def test_isodata_moon_image_negative_float(): + moon = util.img_as_ubyte(data.moon()).astype(np.float64) + moon -= 100 + + assert -14 < threshold_isodata(moon) < -13 + + thresholds = threshold_isodata(moon, return_all=True) + assert_almost_equal( + thresholds, + [ + -13.83789062, + -12.84179688, + -11.84570312, + 22.02148438, + 23.01757812, + 24.01367188, + 38.95507812, + 39.95117188, + ], + ) + + +def test_threshold_minimum(): + camera = util.img_as_ubyte(data.camera()) + + threshold = threshold_minimum(camera) + assert_equal(threshold, 85) + + astronaut = util.img_as_ubyte(data.astronaut()) + threshold = threshold_minimum(astronaut) + assert_equal(threshold, 114) + + +def test_threshold_minimum_histogram(): + camera = util.img_as_ubyte(data.camera()) + hist = histogram(camera.ravel(), 256, source_range='image') + threshold = threshold_minimum(hist=hist) + assert_equal(threshold, 85) + + +def test_threshold_minimum_counts(): + camera = util.img_as_ubyte(data.camera()) + counts, bin_centers = histogram(camera.ravel(), 256, source_range='image') + threshold = threshold_minimum(hist=counts) + assert_equal(threshold, 85) + + +def test_threshold_minimum_synthetic(): + img = np.arange(25 * 25, dtype=np.uint8).reshape((25, 25)) + img[0:9, :] = 50 + img[14:25, :] = 250 + + threshold = threshold_minimum(img) + assert_equal(threshold, 95) + + +def test_threshold_minimum_failure(): + img = np.zeros((16 * 16), dtype=np.uint8) + with pytest.raises(RuntimeError): + threshold_minimum(img) + + +def test_mean(): + img = np.zeros((2, 6)) + img[:, 2:4] = 1 + img[:, 4:] = 2 + assert threshold_mean(img) == 1.0 + + +@pytest.mark.parametrize("dtype", [np.uint8, np.int16, np.float16, np.float32]) +def test_triangle_uniform_images(dtype): + assert threshold_triangle(np.zeros((10, 10), dtype=dtype)) == 0 + assert threshold_triangle(np.ones((10, 10), dtype=dtype)) == 1 + assert threshold_triangle(np.full((10, 10), 2, dtype=dtype)) == 2 + + +def test_triangle_uint_images(): + assert threshold_triangle(np.invert(data.text())) == 151 + assert threshold_triangle(data.text()) == 104 + assert threshold_triangle(data.coins()) == 80 + assert threshold_triangle(np.invert(data.coins())) == 175 + + +def test_triangle_float_images(): + text = data.text() + int_bins = text.max() - text.min() + 1 + # Set nbins to match the uint case and threshold as float. + assert round(threshold_triangle(text.astype(float), nbins=int_bins)) == 104 + # Check that rescaling image to floats in unit interval is equivalent. + assert round(threshold_triangle(text / 255.0, nbins=int_bins) * 255) == 104 + # Repeat for inverted image. + assert ( + round(threshold_triangle(np.invert(text).astype(float), nbins=int_bins)) == 151 + ) + assert ( + round(threshold_triangle(np.invert(text) / 255.0, nbins=int_bins) * 255) == 151 + ) + + +def test_triangle_flip(): + # Depending on the skewness, the algorithm flips the histogram. + # We check that the flip doesn't affect too much the result. + img = data.camera() + inv_img = np.invert(img) + t = threshold_triangle(inv_img) + t_inv_img = inv_img > t + t_inv_inv_img = np.invert(t_inv_img) + + t = threshold_triangle(img) + t_img = img > t + + # Check that most of the pixels are identical + # See numpy #7685 for a future np.testing API + unequal_pos = np.where(t_img.ravel() != t_inv_inv_img.ravel()) + assert len(unequal_pos[0]) / t_img.size < 1e-2 + + +@pytest.mark.parametrize( + "window_size, mean_kernel", + [ + (11, np.full((11,) * 2, 1 / 11**2)), + ((11, 11), np.full((11, 11), 1 / 11**2)), + ((9, 13), np.full((9, 13), 1 / math.prod((9, 13)))), + ((13, 9), np.full((13, 9), 1 / math.prod((13, 9)))), + ((1, 9), np.full((1, 9), 1 / math.prod((1, 9)))), + ], +) +def test_mean_std_2d(window_size, mean_kernel): + image = np.random.rand(256, 256) + m, s = _mean_std(image, w=window_size) + expected_m = ndi.convolve(image, mean_kernel, mode='mirror') + assert_allclose(m, expected_m) + expected_s = ndi.generic_filter(image, np.std, size=window_size, mode='mirror') + assert_allclose(s, expected_s) + + +@pytest.mark.parametrize( + "window_size, mean_kernel", + [ + (5, np.full((5,) * 3, 1 / 5) ** 3), + ((5, 5, 5), np.full((5, 5, 5), 1 / 5**3)), + ((1, 5, 5), np.full((1, 5, 5), 1 / 5**2)), + ((3, 5, 7), np.full((3, 5, 7), 1 / math.prod((3, 5, 7)))), + ], +) +def test_mean_std_3d(window_size, mean_kernel): + image = np.random.rand(40, 40, 40) + m, s = _mean_std(image, w=window_size) + expected_m = ndi.convolve(image, mean_kernel, mode='mirror') + assert_allclose(m, expected_m) + expected_s = ndi.generic_filter(image, np.std, size=window_size, mode='mirror') + assert_allclose(s, expected_s) + + +@pytest.mark.parametrize( + "threshold_func", + [threshold_local, threshold_niblack, threshold_sauvola], +) +@pytest.mark.parametrize("dtype", [np.uint8, np.int16, np.float16, np.float32]) +def test_variable_dtypes(threshold_func, dtype): + r = 255 * np.random.rand(32, 16) + r = r.astype(dtype, copy=False) + + kwargs = {} + if threshold_func is threshold_local: + kwargs = dict(block_size=9) + elif threshold_func is threshold_sauvola: + kwargs = dict(r=128) + + # use double precision result as a reference + expected = threshold_func(r.astype(float), **kwargs) + + out = threshold_func(r, **kwargs) + assert out.dtype == _supported_float_type(dtype) + assert_allclose(out, expected, rtol=1e-5, atol=1e-5) + + +def test_niblack_sauvola_pathological_image(): + # For certain values, floating point error can cause + # E(X^2) - (E(X))^2 to be negative, and taking the square root of this + # resulted in NaNs. Here we check that these are safely caught. + # see https://github.com/scikit-image/scikit-image/issues/3007 + value = 0.03082192 + 2.19178082e-09 + src_img = np.full((4, 4), value).astype(np.float64) + assert not np.any(np.isnan(threshold_niblack(src_img))) + + +def test_bimodal_multiotsu_hist(): + for name in ['camera', 'moon', 'coins', 'text', 'clock', 'page']: + img = getattr(data, name)() + assert threshold_otsu(img) == threshold_multiotsu(img, 2) + + for name in ['chelsea', 'coffee', 'astronaut', 'rocket']: + img = rgb2gray(getattr(data, name)()) + assert threshold_otsu(img) == threshold_multiotsu(img, 2) + + +def test_check_multiotsu_results(): + image = 0.25 * np.array( + [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] + ) + + for idx in range(3, 6): + thr_multi = threshold_multiotsu(image, classes=idx) + assert len(thr_multi) == idx - 1 + + +def test_multiotsu_output(): + image = np.zeros((100, 100), dtype='int') + coords = [(25, 25), (50, 50), (75, 75)] + values = [64, 128, 192] + for coor, val in zip(coords, values): + rr, cc = disk(coor, 20) + image[rr, cc] = val + thresholds = [0, 64, 128] + assert np.array_equal(thresholds, threshold_multiotsu(image, classes=4)) + + +def test_multiotsu_astro_image(): + img = util.img_as_ubyte(data.astronaut()) + with expected_warnings(['grayscale']): + assert_almost_equal(threshold_multiotsu(img), [58, 149]) + + +def test_multiotsu_more_classes_then_values(): + img = np.ones((10, 10), dtype=np.uint8) + with pytest.raises(ValueError): + threshold_multiotsu(img, classes=2) + img[:, 3:] = 2 + with pytest.raises(ValueError): + threshold_multiotsu(img, classes=3) + img[:, 6:] = 3 + with pytest.raises(ValueError): + threshold_multiotsu(img, classes=4) + + +def test_multiotsu_lut(): + for classes in [2, 3, 4]: + for name in ['camera', 'moon', 'coins', 'text', 'clock', 'page']: + img = getattr(data, name)() + prob, bin_centers = histogram( + img.ravel(), nbins=256, source_range='image', normalize=True + ) + prob = prob.astype('float32') + + result_lut = _get_multiotsu_thresh_indices_lut(prob, classes - 1) + result = _get_multiotsu_thresh_indices(prob, classes - 1) + + assert np.array_equal(result_lut, result) + + +def test_multiotsu_missing_img_and_hist(): + with pytest.raises(Exception): + threshold_multiotsu() + + +def test_multiotsu_hist_parameter(): + for classes in [2, 3, 4]: + for name in ['camera', 'moon', 'coins', 'text', 'clock', 'page']: + img = getattr(data, name)() + sk_hist = histogram(img, nbins=256) + # + thresh_img = threshold_multiotsu(img, classes) + thresh_sk_hist = threshold_multiotsu(classes=classes, hist=sk_hist) + assert np.allclose(thresh_img, thresh_sk_hist) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_unsharp_mask.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_unsharp_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..676d1abf2151fa61550c872866d18f4994ba2984 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_unsharp_mask.py @@ -0,0 +1,157 @@ +import warnings + +import numpy as np +import pytest + +from skimage._shared.utils import _supported_float_type +from skimage.filters import unsharp_mask + + +@pytest.mark.parametrize( + "shape,multichannel", + [ + ((29,), False), + ((40, 4), True), + ((32, 32), False), + ((29, 31, 3), True), + ((13, 17, 4, 8), False), + ], +) +@pytest.mark.parametrize( + "dtype", + [ + np.uint8, + np.int8, + np.uint16, + np.int16, + np.uint32, + np.int32, + np.uint64, + np.int64, + np.float32, + np.float64, + ], +) +@pytest.mark.parametrize("radius", [0, 0.1, 2.0]) +@pytest.mark.parametrize("amount", [0.0, 0.5, 2.0, -1.0]) +@pytest.mark.parametrize("offset", [-1.0, 0.0, 1.0]) +@pytest.mark.parametrize("preserve", [False, True]) +def test_unsharp_masking_output_type_and_shape( + radius, amount, shape, multichannel, dtype, offset, preserve +): + array = np.random.random(shape) + array = (array + offset) * 128 + with warnings.catch_warnings(): + # Ignore arch specific warning on arm64, armhf, ppc64el, riscv64, s390x + # https://github.com/scikit-image/scikit-image/issues/7391 + warnings.filterwarnings( + action="ignore", + category=RuntimeWarning, + message="invalid value encountered in cast", + ) + array = array.astype(dtype) + + if (preserve is False) and (dtype in [np.float32, np.float64]): + array /= max(np.abs(array).max(), 1.0) + channel_axis = -1 if multichannel else None + output = unsharp_mask( + array, radius, amount, preserve_range=preserve, channel_axis=channel_axis + ) + assert output.dtype in [np.float32, np.float64] + assert output.shape == shape + + +@pytest.mark.parametrize( + "shape,multichannel", [((32, 32), False), ((15, 15, 2), True), ((17, 19, 3), True)] +) +@pytest.mark.parametrize("radius", [(0.0, 0.0), (1.0, 1.0), (2.0, 1.5)]) +@pytest.mark.parametrize("preserve", [False, True]) +def test_unsharp_masking_with_different_radii(radius, shape, multichannel, preserve): + amount = 1.0 + dtype = np.float64 + array = (np.random.random(shape) * 96).astype(dtype) + if preserve is False: + array /= max(np.abs(array).max(), 1.0) + channel_axis = -1 if multichannel else None + output = unsharp_mask( + array, radius, amount, preserve_range=preserve, channel_axis=channel_axis + ) + assert output.dtype in [np.float32, np.float64] + assert output.shape == shape + + +@pytest.mark.parametrize( + "shape,channel_axis", + [ + ((16, 16), None), + ((15, 15, 2), -1), + ((13, 17, 3), -1), + ((2, 15, 15), 0), + ((3, 13, 17), 0), + ], +) +@pytest.mark.parametrize("offset", [-5, 0, 5]) +@pytest.mark.parametrize("preserve", [False, True]) +def test_unsharp_masking_with_different_ranges(shape, offset, channel_axis, preserve): + radius = 2.0 + amount = 1.0 + dtype = np.int16 + array = (np.random.random(shape) * 5 + offset).astype(dtype) + negative = np.any(array < 0) + output = unsharp_mask( + array, radius, amount, preserve_range=preserve, channel_axis=channel_axis + ) + if preserve is False: + assert np.any(output <= 1) + assert np.any(output >= -1) + if negative is False: + assert np.any(output >= 0) + assert output.dtype in [np.float32, np.float64] + assert output.shape == shape + + +@pytest.mark.parametrize( + "shape,channel_axis", [((16, 16), None), ((15, 15, 2), -1), ((13, 17, 3), -1)] +) +@pytest.mark.parametrize("offset", [-5, 0, 5]) +@pytest.mark.parametrize("preserve", [False, True]) +def test_unsharp_masking_with_different_ranges_deprecated( + shape, offset, channel_axis, preserve +): + radius = 2.0 + amount = 1.0 + dtype = np.int16 + array = (np.random.random(shape) * 5 + offset).astype(dtype) + negative = np.any(array < 0) + output = unsharp_mask( + array, radius, amount, channel_axis=channel_axis, preserve_range=preserve + ) + if preserve is False: + assert np.any(output <= 1) + assert np.any(output >= -1) + if negative is False: + assert np.any(output >= 0) + assert output.dtype in [np.float32, np.float64] + assert output.shape == shape + + +@pytest.mark.parametrize( + "shape,channel_axis", [((16, 16), None), ((15, 15, 2), -1), ((13, 17, 3), -1)] +) +@pytest.mark.parametrize("preserve", [False, True]) +@pytest.mark.parametrize("dtype", [np.uint8, np.float16, np.float32, np.float64]) +def test_unsharp_masking_dtypes(shape, channel_axis, preserve, dtype): + radius = 2.0 + amount = 1.0 + array = (np.random.random(shape) * 10).astype(dtype, copy=False) + negative = np.any(array < 0) + output = unsharp_mask( + array, radius, amount, preserve_range=preserve, channel_axis=channel_axis + ) + if preserve is False: + assert np.any(output <= 1) + assert np.any(output >= -1) + if negative is False: + assert np.any(output >= 0) + assert output.dtype == _supported_float_type(dtype) + assert output.shape == shape diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_window.py b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_window.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbb8d8b9a4ba80bc0b4c5aff7d6d4e4de29159c --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/filters/tests/test_window.py @@ -0,0 +1,54 @@ +import numpy as np +import pytest +from scipy.signal import get_window + +from skimage.filters import window + + +@pytest.mark.parametrize("size", [5, 6]) +@pytest.mark.parametrize("ndim", [2, 3, 4]) +def test_window_shape_isotropic(size, ndim): + w = window('hann', (size,) * ndim) + assert w.ndim == ndim + assert w.shape[1:] == w.shape[:-1] + for i in range(1, ndim - 1): + assert np.allclose(w.sum(axis=0), w.sum(axis=i)) + + +@pytest.mark.parametrize("shape", [(8, 16), (16, 8), (2, 3, 4)]) +def test_window_shape_anisotropic(shape): + w = window('hann', shape) + assert w.shape == shape + + +@pytest.mark.parametrize("shape", [[17, 33], [17, 97]]) +def test_window_anisotropic_amplitude(shape): + w = window(('tukey', 0.8), shape) + + # The shape is stretched to give approximately the same range on each axis, + # so the center profile should have a similar mean value. + profile_w = w[w.shape[0] // 2, :] + profile_h = w[:, w.shape[1] // 2] + assert abs(profile_w.mean() - profile_h.mean()) < 0.01 + + +@pytest.mark.parametrize("wintype", [16, 'triang', ('tukey', 0.8)]) +def test_window_type(wintype): + w = window(wintype, (9, 9)) + assert w.ndim == 2 + assert w.shape[1:] == w.shape[:-1] + assert np.allclose(w.sum(axis=0), w.sum(axis=1)) + + +@pytest.mark.parametrize("size", [10, 11]) +def test_window_1d(size): + w = window('hann', size) + w1 = get_window('hann', size, fftbins=False) + assert np.allclose(w, w1) + + +def test_window_invalid_shape(): + with pytest.raises(ValueError): + window(10, shape=(-5, 10)) + with pytest.raises(ValueError): + window(10, shape=(1.3, 2.0))