Skip to content

Fix cholesky decomposition for complex dtype - #12348

Closed
kaiisfree wants to merge 1 commit into
dask:mainfrom
kaiisfree:fix/cholesky-complex-dtype
Closed

kaiisfree wants to merge 1 commit into
dask:mainfrom
kaiisfree:fix/cholesky-complex-dtype

Conversation

@kaiisfree

Copy link
Copy Markdown

Summary

  • Fix incorrect cholesky decomposition for complex-valued matrices
  • The blocked cholesky algorithm used plain transpose (np.transpose) where conjugate transpose is mathematically required
  • NumPy's cholesky satisfies A = L @ L*.T (Hermitian), but dask used plain transpose giving wrong results for complex dtypes
  • Added _conj_transpose helper that applies .T.conj() — this is a no-op for real matrices since conj() on real data is identity

Test plan

  • Added parametrized test test_cholesky_complex with complex Hermitian positive-definite matrices
  • Verified both lower=True and lower=False results match NumPy's np.linalg.cholesky
  • Existing real-valued cholesky tests continue to pass

Fixes #12335

🤖 Generated with Claude Code

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]>
@github-actions

github-actions Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

Unit Test Results

See 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
 18 296 tests + 3   16 941 ✅ + 3   1 272 💤 ±0  83 ❌ ±0 
317 568 runs  +48  273 776 ✅ +44  43 709 💤 +4  83 ❌ ±0 

For more details on these failures, see this check.

Results for commit b5700d1. ± Comparison against base commit 5843716.

@ncclementi

Copy link
Copy Markdown
Member

@kaiisfree would you mind fixing the issues that are causing CI to fail?

Comment thread dask/array/linalg.py
return solve(a, eye(a.shape[0], chunks=a.chunks[0][0]))


def _conj_transpose(a):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@nicrie nicrie May 8, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For real numbers .conj() is the identity function. I briefly checked in numpy, and for a real array a,

a.conj() is a  # returns True

so 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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nicrie keep this comment in mind when you attempt the implementation.

@ncclementi

Copy link
Copy Markdown
Member

@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.

@nicrie

nicrie commented May 21, 2026

Copy link
Copy Markdown
Contributor

I will give it a try @ncclementi

@nicrie

nicrie commented May 23, 2026

Copy link
Copy Markdown
Contributor

hey @ncclementi I did a quick check and benchmarked the computing time for transpose with/wo conj() operation for both real and complex valued arrays. To my surprise, conj() seems to double the computing time even for real arrays.

performance_conj_transpose_dask
Code to reproduce dask plot

Transpose benchmarking

import 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:

performance_conj_transpose_numpy

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.

@crusaderky

Copy link
Copy Markdown
Collaborator

;) 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.
Please add a 2-liner conditional code path that kicks in just for complex.

@nicrie

nicrie commented May 25, 2026

Copy link
Copy Markdown
Contributor

@crusaderky @ncclementi I was intrigued by that doubling of computing time for conj(), so I dug into this aa bit more. My earlier benchmark was measuring Dask x.conj().transpose(), not the block-local np.transpose(block).conj() helper used by this PR. I reran the benchmark for the actual code path, and the updated plot shows no meaningful slowdown for real arrays. Thats now also consistent with the numpy code.

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)

performance_conj_transpose_dask

Note the additional log scale on x for this plot in contrast to the previous plots above

Code to reproduce dask plot

Transpose benchmarking

import 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)

@nicrie

nicrie commented May 25, 2026

Copy link
Copy Markdown
Contributor

Opened PR #12416 in favour of this one.

@crusaderky

Copy link
Copy Markdown
Collaborator

Superseded by #12416

@crusaderky crusaderky closed this May 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cholesky incorrect for complex dtype

4 participants