{"record":{"id":"c624e3edda7b7933","repo":"jax-ml/jax","slug":"n-must-be-a-positive-power-of-2-got-n","errorCode":null,"errorMessage":"n must be a positive power of 2; got {n}.","messagePattern":"n must be a positive power of 2; got (.+?)\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"jax/_src/scipy/linalg.py","lineNumber":3161,"sourceCode":"  construction: :math:`H_1 = [[1]]`, and\n  :math:`H_{2m} = \\begin{bmatrix} H_m & H_m \\\\ H_m & -H_m \\end{bmatrix}`.\n\n  Args:\n    n: size of the matrix. Must be a positive power of 2.\n    dtype: output dtype. Defaults to ``int``.\n\n  Returns:\n    A Hadamard matrix of shape ``(n, n)``.\n\n  Examples:\n    >>> jax.scipy.linalg.hadamard(4)\n    Array([[ 1,  1,  1,  1],\n           [ 1, -1,  1, -1],\n           [ 1,  1, -1, -1],\n           [ 1, -1, -1,  1]], dtype=int32)\n  \"\"\"\n  if n < 1 or not math.log2(n).is_integer():\n    raise ValueError(\n        f\"n must be a positive power of 2; got {n}.\")\n  lg2 = int(math.log2(n))\n  H = jnp.ones((1, 1), dtype=dtype)\n  for _ in range(lg2):\n    H = jnp.block([[H, H], [H, -H]])\n  return H\n\n\n@jit(static_argnames=(\"n\", \"scale\", \"dtype\"))\ndef dft(n: int, scale: str | None = None, *,\n        dtype: DTypeLike | None = None) -> Array:\n  r\"\"\"Construct an n-by-n discrete Fourier transform matrix.\n\n  JAX implementation of :func:`scipy.linalg.dft`.\n\n  The DFT matrix :math:`W_n` has entries :math:`W_{ij} = \\omega^{ij}`, where\n  :math:`\\omega = e^{-2\\pi i / n}` is the primitive n-th root of unity, for\n  :math:`0 \\le i, j < n`.","sourceCodeStart":3143,"sourceCodeEnd":3179,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/scipy/linalg.py#L3143-L3179","documentation":"jax.scipy.linalg.hadamard requires n to be a positive power of 2 because the matrix is built by lg2 = log2(n) recursive Sylvester blocking steps. math.log2(n).is_integer() fails for non-powers (and math.log2 of 0/negatives errors, hence the n < 1 guard).","triggerScenarios":"Calling hadamard(3), hadamard(12), hadamard(0), or hadamard(-4); computing n from data sizes like hadamard(num_features).","commonSituations":"Using Hadamard transforms in ML pipelines where the dimension is the feature count (e.g. 768) rather than a padded power of two.","solutions":["Pad n up to the next power of two (e.g. n = 1 << (n-1).bit_length()) and slice the result if needed","Fix n to a power of 2 like 2**k in experiment configs","Validate n before calling"],"exampleFix":"# before\nH = linalg.hadamard(x.shape[1])  # 768 -> error\n# after\np = 1 << (x.shape[1] - 1).bit_length()\nH = linalg.hadamard(p)[:x.shape[1], :x.shape[1]]  # or pad x instead","handlingStrategy":"validation","validationCode":"assert n >= 1 and (n & (n - 1)) == 0, f'n={n} not a power of 2'","typeGuard":"def is_pow2(n: int) -> bool: return n >= 1 and (n & (n - 1)) == 0","tryCatchPattern":null,"preventionTips":["Precompute power-of-two sizes as 2**k in configs"],"tags":["jax","scipy","linalg","matrix","argument-validation"],"backgroundTag":"argument-out-of-range","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}