Repository navigation
Conversation
The blocked cholesky algorithm used plain transpose (np.transpose) where conjugate transpose is mathematically required. For complex Hermitian positive-definite matrices, the Cholesky decomposition satisfies A = L @ L*.T (not A = L @ L.T). This caused incorrect results for complex dtypes. Replace np.transpose with a new _conj_transpose helper that applies conjugate transpose. This is a no-op for real matrices since conj() on real data returns the same values. Add tests verifying complex cholesky for both lower and upper triangular forms. Fixes dask#12335 Co-Authored-By: Claude Opus 4.6 <[email protected]>
Unit Test ResultsSee test report for an extended history of previous test failures. This is useful for diagnosing flaky tests. 21 files ± 0 21 suites ±0 5h 26m 33s ⏱️ - 6m 9s For more details on these failures, see this check. Results for commit b5700d1. ± Comparison against base commit 5843716. |
|
@kaiisfree would you mind fixing the issues that are causing CI to fail? |
| return solve(a, eye(a.shape[0], chunks=a.chunks[0][0])) | ||
|
|
||
|
|
||
| def _conj_transpose(a): |
There was a problem hiding this comment.
I see ho this is more generic and would fix the issue, I'm not sure we would want to be doing this for the case where we only have real numbers.
@nicrie and @philipdkennedy maybe you might have some opinions here
There was a problem hiding this comment.
For real numbers .conj() is the identity function. I briefly checked in numpy, and for a real array a,
a.conj() is a # returns Trueso it doesn't seem like a copy either. I guess a.conj() is a cheap operation for real arrays. That would mean we fix the bug without getting any (computational) penalties. Perhaps someone could confirm this?
There was a problem hiding this comment.
Maybe @crusaderky can chime in here. DO you have any thoughts on this patch?
I see the original user is not replying, but the fix seems ok enough to take as inspiration. If this approach is acceptable, I can open a PR that takes care of the fix, and fixing CI.
There was a problem hiding this comment.
As long as a.conj() resolves in microseconds for real numbers, I don't have an issue with it. But it would definitely warrant a comment in the function.
There was a problem hiding this comment.
@nicrie keep this comment in mind when you attempt the implementation.
|
@nicrie looks like the original author of the PR is not responded, probably an AI PR, and not willing to take it across the line an discuss. If you are interested in this fix, would you be open to open a separate PR with the fix, you can take this one as inspiration and open a separate one. |
|
I will give it a try @ncclementi |
|
hey @ncclementi I did a quick check and benchmarked the computing time for transpose with/wo
Code to reproduce dask plotTranspose benchmarkingimport gc
import time
import dask
import dask.array as da
import matplotlib.pyplot as plt
import numpy as np
SIZES = [250, 500, 1000, 2000, 4000, 6000, 8000, 10000]
OPERATIONS = {
"transpose": "transpose()",
"conj_transpose": "conj().transpose()",
}
REPEATS = 15
CHUNK_EDGE = 500
WARMUP_RUNS = 3
SCHEDULER = "single-threaded"
SEED = 42
def build_source_array(
edge_length: int, chunk_edge: int, *, kind: str, seed: int
) -> da.Array:
rng = np.random.default_rng(seed)
shape = (edge_length, edge_length)
chunks = (min(chunk_edge, edge_length), min(chunk_edge, edge_length))
if kind == "real":
source = rng.standard_normal(shape)
elif kind == "complex":
real_part = rng.standard_normal(shape)
imag_part = rng.standard_normal(shape)
source = real_part + 1j * imag_part
else:
raise ValueError(f"Unsupported array kind: {kind}")
return da.from_array(source, chunks=chunks, name=False)
def build_transformed_array(array: da.Array, operation: str) -> da.Array:
if operation == "transpose":
return array.transpose()
if operation == "conj_transpose":
return array.conj().transpose()
def run_operation(array: da.Array, operation: str, scheduler: str) -> None:
transformed = build_transformed_array(array, operation)
_ = transformed.compute(scheduler=scheduler)
def benchmark_kind(
*,
edge_length: int,
chunk_edge: int,
repeats: int,
warmup_runs: int,
operation: str,
scheduler: str,
seed: int,
kind: str,
) -> list[float]:
array = build_source_array(
edge_length=edge_length,
chunk_edge=chunk_edge,
kind=kind,
seed=seed,
)
samples: list[float] = []
with dask.config.set(scheduler=scheduler):
for _ in range(warmup_runs):
run_operation(array, operation, scheduler)
gc.collect()
for _ in range(repeats):
start = time.perf_counter()
run_operation(array, operation, scheduler)
samples.append(time.perf_counter() - start)
gc.collect()
return samples
def summarize_samples(samples: list[float]) -> float:
return float(np.min(samples))
samples_by_case: dict[tuple[str, str], list[list[float]]] = {
(kind, operation): [] for kind in ("real", "complex") for operation in OPERATIONS
}
for offset, edge_length in enumerate(SIZES):
for kind in ("real", "complex"):
kind_seed = SEED + (offset * 2) + (1 if kind == "complex" else 0)
for operation in OPERATIONS:
case_samples = benchmark_kind(
edge_length=edge_length,
chunk_edge=CHUNK_EDGE,
repeats=REPEATS,
warmup_runs=WARMUP_RUNS,
operation=operation,
scheduler=SCHEDULER,
seed=kind_seed,
kind=kind,
)
samples_by_case[(kind, operation)].append(case_samples)
# %%
fig, ax = plt.subplots(figsize=(10, 6))
line_styles = {
("real", "transpose"): {"color": "tab:blue", "linestyle": "-", "marker": "o"},
("real", "conj_transpose"): {
"color": "tab:blue",
"linestyle": "--",
"marker": "s",
},
("complex", "transpose"): {
"color": "tab:orange",
"linestyle": "-",
"marker": "o",
},
("complex", "conj_transpose"): {
"color": "tab:orange",
"linestyle": "--",
"marker": "s",
},
}
for kind in ("real", "complex"):
for operation, operation_label in OPERATIONS.items():
case_key = (kind, operation)
case_times = [
summarize_samples(samples) for samples in samples_by_case[case_key]
]
ax.plot(
SIZES,
case_times,
linewidth=2,
label=f"{kind} {operation_label}",
**line_styles[case_key],
)
ax.set_xlabel("Square array edge length N for N x N arrays")
ax.set_ylabel("Time (seconds)")
ax.set_title(f"dask transpose benchmark ({SCHEDULER}, minimum of {REPEATS} runs)")
ax.grid(True, alpha=0.3)
ax.set_yscale("log")
ax.legend()
fig.tight_layout()
fig.savefig("performance_conj_transpose_dask.png", dpi=160)
plt.close(fig)I made the same computations using numpy instead of dask, just for comparison:
My takeaway is that I don't understand enough from the internals of numpy/dask to explain where these differences come from ;) But in the end it's your call as dask developers if you can accept a doubling of computation time for real arrays to fix the complex case. |
Hard no. |
|
@crusaderky @ncclementi I was intrigued by that doubling of computing time for So the previous performance concern does not seem to apply to this implementation. Updated plot and repro code attached. I'll prepare a clean PR using this implentation (without a complex-only conditional)
Note the additional log scale on x for this plot in contrast to the previous plots above Code to reproduce dask plotTranspose benchmarkingimport gc
import time
import dask
import dask.array as da
import matplotlib.pyplot as plt
import numpy as np
SIZES = [250, 500, 1000, 2000, 4000, 6000, 8000, 10000]
OPERATIONS = {
"block_transpose": "blockwise transpose",
"block_conj_transpose": "blockwise transpose().conj()",
}
REPEATS = 15
CHUNK_EDGE = 500
WARMUP_RUNS = 3
SCHEDULER = "single-threaded"
SEED = 42
def build_source_array(
edge_length: int, chunk_edge: int, *, kind: str, seed: int
) -> da.Array:
rng = np.random.default_rng(seed)
shape = (edge_length, edge_length)
chunks = (min(chunk_edge, edge_length), min(chunk_edge, edge_length))
if kind == "real":
source = rng.standard_normal(shape)
elif kind == "complex":
real_part = rng.standard_normal(shape)
imag_part = rng.standard_normal(shape)
source = real_part + 1j * imag_part
else:
raise ValueError(f"Unsupported array kind: {kind}")
return da.from_array(source, chunks=chunks, name=False)
def _transpose_only(block):
return np.transpose(block)
def _conj_transpose(a):
return np.transpose(a).conj()
def build_transformed_array(array: da.Array, operation: str) -> da.Array:
if operation == "block_transpose":
func = _transpose_only
elif operation == "block_conj_transpose":
func = _conj_transpose
else:
raise ValueError(f"Unsupported operation: {operation}")
return da.blockwise(func, "ji", array, "ij", dtype=array.dtype)
def run_operation(array: da.Array, operation: str, scheduler: str) -> None:
transformed = build_transformed_array(array, operation)
_ = transformed.compute(scheduler=scheduler)
def benchmark_kind(
*,
edge_length: int,
chunk_edge: int,
repeats: int,
warmup_runs: int,
operation: str,
scheduler: str,
seed: int,
kind: str,
) -> list[float]:
array = build_source_array(
edge_length=edge_length,
chunk_edge=chunk_edge,
kind=kind,
seed=seed,
)
samples: list[float] = []
with dask.config.set(scheduler=scheduler):
for _ in range(warmup_runs):
run_operation(array, operation, scheduler)
gc.collect()
for _ in range(repeats):
start = time.perf_counter()
run_operation(array, operation, scheduler)
samples.append(time.perf_counter() - start)
gc.collect()
return samples
def summarize_samples(samples: list[float]) -> float:
return float(np.min(samples))
samples_by_case: dict[tuple[str, str], list[list[float]]] = {
(kind, operation): [] for kind in ("real", "complex") for operation in OPERATIONS
}
for offset, edge_length in enumerate(SIZES):
for kind in ("real", "complex"):
kind_seed = SEED + (offset * 2) + (1 if kind == "complex" else 0)
for operation in OPERATIONS:
case_samples = benchmark_kind(
edge_length=edge_length,
chunk_edge=CHUNK_EDGE,
repeats=REPEATS,
warmup_runs=WARMUP_RUNS,
operation=operation,
scheduler=SCHEDULER,
seed=kind_seed,
kind=kind,
)
samples_by_case[(kind, operation)].append(case_samples)
# %%
fig, ax = plt.subplots(figsize=(10, 6))
line_styles = {
("real", "block_transpose"): {"color": "tab:blue", "linestyle": "-", "marker": "o"},
("real", "block_conj_transpose"): {
"color": "tab:blue",
"linestyle": "--",
"marker": "s",
},
("complex", "block_transpose"): {
"color": "tab:orange",
"linestyle": "-",
"marker": "o",
},
("complex", "block_conj_transpose"): {
"color": "tab:orange",
"linestyle": "--",
"marker": "s",
},
}
for kind in ("real", "complex"):
for operation, operation_label in OPERATIONS.items():
case_key = (kind, operation)
case_times = [
summarize_samples(samples) for samples in samples_by_case[case_key]
]
ax.plot(
SIZES,
case_times,
linewidth=2,
label=f"{kind} {operation_label}",
**line_styles[case_key],
)
ax.set_xlabel("Square array edge length N for N x N arrays")
ax.set_ylabel("Time (seconds)")
ax.set_title(f"dask transpose benchmark ({SCHEDULER}, minimum of {REPEATS} runs)")
ax.grid(True, alpha=0.3)
ax.set_yscale("log")
ax.set_xscale("log")
ax.legend()
fig.tight_layout()
fig.savefig("performance_conj_transpose_dask.png", dpi=160)
plt.close(fig) |
|
Opened PR #12416 in favour of this one. |
|
Superseded by #12416 |



Summary
np.transpose) where conjugate transpose is mathematically requiredA = L @ L*.T(Hermitian), but dask used plain transpose giving wrong results for complex dtypes_conj_transposehelper that applies.T.conj()— this is a no-op for real matrices sinceconj()on real data is identityTest plan
test_cholesky_complexwith complex Hermitian positive-definite matriceslower=Trueandlower=Falseresults match NumPy'snp.linalg.choleskyFixes #12335
🤖 Generated with Claude Code