Metadata-Version: 2.4
Name: pyfwht
Version: 3.0.0
Summary: Fast Walsh-Hadamard Transform with CPU, OpenMP, and CUDA backends
Author-email: Hosein Hadipour <hsn.hadipour@gmail.com>
License: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/hadipourh/fwht
Project-URL: Repository, https://github.com/hadipourh/fwht
Project-URL: Documentation, https://github.com/hadipourh/fwht/blob/main/python/README.md
Project-URL: Issues, https://github.com/hadipourh/fwht/issues
Keywords: walsh-hadamard,fwht,cryptanalysis,boolean-functions,cuda,gpu,simd,vectorization
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: C
Classifier: Programming Language :: C++
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Security :: Cryptography
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Provides-Extra: gpu
Requires-Dist: torch>=2.0.0; extra == "gpu"
Provides-Extra: all
Requires-Dist: pytest>=7.0; extra == "all"
Requires-Dist: pytest-benchmark>=4.0; extra == "all"
Requires-Dist: black>=23.0; extra == "all"
Requires-Dist: mypy>=1.0; extra == "all"
Requires-Dist: ruff>=0.1.0; extra == "all"
Requires-Dist: torch>=2.0.0; extra == "all"
Dynamic: license-file

# pyfwht - Fast Walsh-Hadamard Transform for Python

[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)

Python bindings for the high-performance libfwht library, providing Fast Walsh-Hadamard Transform with NumPy integration and support for CPU (SIMD), OpenMP, and CUDA backends.

## Features

- **NumPy integration**: In-place operations use the supplied array; allocating operations may copy inputs
- **Multiple backends**: Automatic selection or explicit choice of CPU (SIMD), OpenMP, or GPU (CUDA)
- **Multi-precision GPU**: fp64 (cryptographic), fp32 (balanced), fp16 (maximum speed on supported Tensor Core GPUs; measured gains are workload-dependent)
- **All data types**: Support for `int8`, `int32`, and `float64` with overflow protection
- **Boolean function analysis**: Convenience functions for cryptographic applications
- **Bit-packed Boolean WHT**: Compute WHT directly from `uint64`-packed truth tables via `fwht.fwht_boolean_packed()` (use `fwht.fwht_boolean_packed_backend(..., fwht.Backend.GPU)` to expand on the device for n ≤ 65536)
- **GPU-resident Boolean contexts**: repeated `fwht.fwht_boolean_packed_backend(..., fwht.Backend.GPU)` calls automatically reuse the CUDA buffers via `fwht_gpu_boolean_context_*`, eliminating per-call allocations on S-box workloads
- **High performance**: 
  - GPU fp16 and fp32 on GPU-resident PyTorch tensors through DLPack (zero-copy); measured GOps/s for each GPU are recorded in [`bench/benchmarks.md`](../bench/benchmarks.md)
  - Tensor Core kernels: n=256, 512, 1024, 2048, 4096, 8192, 16384, **32768** (Meta-inspired implementation)
  - DLPack support: avoids the host-to-device and device-to-host copies of the NumPy path
  - Recursive cache-efficient algorithm (512-element L1-optimized base case)
  - Task-based OpenMP parallelism (2-3× speedup on 4-8 cores)
  - Software prefetching and cache-aligned memory allocation
  - SIMD optimization (AVX2/SSE2/NEON selected at build time)
- **Easy to use**: Pythonic API with comprehensive error handling and numerical documentation

## Installation

### Requirements

- Python 3.8+
- NumPy >= 1.20.0
- C99 and C++17 compilers (gcc or clang)
- Python development headers matching the build interpreter (`python3-devel` on
  AlmaLinux/RHEL, `python3-dev` on Debian/Ubuntu). On clusters, a Python module
  that includes development headers can supply these without a system install.
- Optional: OpenMP-capable compiler for multi-threading
- Optional: CUDA toolkit (nvcc) for GPU support

### From PyPI

```bash
# Install (automatically enables CUDA if nvcc is found)
pip install pyfwht

# On Linux, you may need to build from source for CUDA support
pip install pyfwht --no-binary :all:

# Disable CUDA even if available
USE_CUDA=0 pip install pyfwht --no-binary :all:
```

### From Source

```bash
git clone https://github.com/hadipourh/fwht libfwht
cd libfwht/python
pip install -e .  # Auto-detects CUDA if nvcc is available

# To install PyTorch as a DLPack producer (other CUDA producers also work):
pip install -e ".[gpu]"  # Installs torch for DLPack GPU support

# Force CUDA on/off
USE_CUDA=1 pip install -e .  # Require CUDA; fails if nvcc is unavailable
USE_CUDA=0 pip install -e .  # Force disable
```

The extension compiles the library sources as C99 and links them into the C++17
binding. Source distributions include the library sources and build independently
of the repository. Builds use baseline CPU instructions; opt into a local machine's
instruction set with `FWHT_NATIVE=1`. `USE_OPENMP=1` requires a successful compiler
and runtime probe; `USE_OPENMP=0` or `NO_OPENMP=1` disables OpenMP. Automatic mode
falls back to a serial CPU build if OpenMP is unavailable.

### Array and concurrency contracts

In-place transforms require a NumPy array with the exact native dtype, writable
C-contiguous storage, and alignment suitable for that dtype. Wrong dtypes,
strided or reversed views, read-only arrays and misaligned buffers raise an
exception before computation. Batch arrays must not overlap. FP16 GPU calls
accept native `float16` arrays or `uint16` arrays containing raw binary16 bits.

Allocating transforms and read-only Boolean/S-box inputs may copy or convert
their inputs, including strided views. The returned output owns its storage.
Native computation releases the GIL: callers must not mutate, resize or free
participating arrays concurrently. Python context methods serialize access to
the same context, and using a closed context raises an exception.

`Context(normalize=True)` applies `1/sqrt(n)` scaling to double transforms and
rejects integer transforms. Errors during computation may leave partially
modified data; only a successful call guarantees a complete result.

`has_cuda_support()` reports compiled support and `has_gpu()` checks current
runtime availability. `set_backend_thresholds(openmp_elements, gpu_elements)`
and `get_backend_thresholds()` configure automatic dispatch explicitly. The
library reads no threshold file implicitly and is quiet unless
`FWHT_LOG_DISPATCH=1` is set.

The DLPack adapters accept an unconsumed legacy `dltensor` capsule with a
two-dimensional, C-contiguous CUDA tensor and one lane per element. They honor
`byte_offset` and the declared device, validate before taking ownership, and
consume each capsule once. The caller grants writable access; legacy capsules
cannot describe read-only tensors. These synchronous adapters wait for producer
work on that device and for the transform to finish. They avoid data copies but
do not provide asynchronous stream overlap. Versioned capsules are not supported.
Call `gpu_release_caches()` before resetting the CUDA runtime when convenience
GPU APIs have been used.

## Quick Start

### Basic Transform

```python
import numpy as np
import pyfwht as fwht

# Create data (must be power of 2 length)
data = np.array([1, -1, -1, 1, -1, 1, 1, -1], dtype=np.int32)

# In-place transform
fwht.fwht_i32(data)
print(data)  # Transformed coefficients
```

### Backend tuning (optional)

AUTO defaults to 8192 elements for OpenMP and 1048576 for GPU. For batches,
these thresholds apply to the total element count. Set them explicitly with
`fwht.set_backend_thresholds(openmp_elements=8192, gpu_elements=1048576)` and
inspect them with `fwht.get_backend_thresholds()`. The library does not read
configuration files from the working directory. `make tune-backend` produces
measurement data that applications may use when choosing explicit thresholds.

### Boolean Function Analysis

```python
import numpy as np
import pyfwht as fwht

# Example: f(x) for x in {0,1}^4
truth_table = np.array([0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0], dtype=np.uint8)

# Compute Walsh-Hadamard coefficients
# For signed convention: 0 → +1, 1 → -1
wht = fwht.fwht_from_bool(truth_table, signed_rep=True)

# Find best linear approximation
n = int(np.log2(len(truth_table)))  # Number of input bits
best_idx = np.argmax(np.abs(wht))
best_wht = wht[best_idx]

# Compute correlation: cor(f, ℓ_u) = W_f(u) / 2^n
correlation = best_wht / (2**n)

# Compute bias: ε = W_f(u) / 2^(n+1)
bias = best_wht / (2**(n+1))

print(f"Best linear mask u: {best_idx:0{n}b}")
print(f"WHT coefficient: {best_wht}")
print(f"Correlation: {correlation:.4f}")
print(f"Bias: {bias:.4f}")
print(f"Linear probability: {0.5 + bias:.4f}")
```

### Batch Processing: Computing Nonlinearity

Analyze cryptographic properties of Boolean functions:

```python
import numpy as np
import pyfwht as fwht

# Generate 1000 random Boolean functions
num_vars = 8  # Number of input variables
num_functions = 1000
functions = np.random.randint(0, 2, size=(num_functions, 2**num_vars), dtype=np.uint8)

# Compute nonlinearity for all functions
nonlinearities = []
for func in functions:
    # fwht_from_bool computes WHT coefficients with signed convention
    wht = fwht.fwht_from_bool(func, signed_rep=True)
    
    # Nonlinearity: NL(f) = 2^(n-1) - (1/2)·max|W_f(u)|
    # For n-variable function, length of truth table is 2^n
    max_abs_wht = np.max(np.abs(wht))
    nl = 2**(num_vars - 1) - max_abs_wht // 2
    nonlinearities.append(nl)

print(f"Average nonlinearity: {np.mean(nonlinearities):.2f}")
print(f"Max nonlinearity: {max(nonlinearities)}")
print(f"Min nonlinearity: {min(nonlinearities)}")
print(f"Theoretical max for {num_vars}-bit functions: {2**(num_vars-1) - 2**(num_vars//2 - 1)}")
```

### Vectorial S-box Analysis

Use the S-box helpers to compute Boolean component spectra and full LAT metrics. Each returns a tuple of a metrics dict and a NumPy array (or `None` when the array is not requested):

```python
import numpy as np
import pyfwht as fwht

# 3-bit identity S-box
table = np.arange(8, dtype=np.uint32)

components, spectra = fwht.sbox_analyze_components(
  table,
  backend=fwht.Backend.CPU,
  profile_timings=True,
  return_spectra=True,
)
lat_metrics, lat_matrix = fwht.sbox_analyze_lat(
  table,
  backend=fwht.Backend.CPU,
  profile_timings=True,
  return_lat=True,
)

print("m_bits", components["m_bits"])
print("n_bits", components["n_bits"])
print("max_walsh", components["max_walsh"])
print("lat_max", lat_metrics["lat_max"])

# Spectra shape: (n_bits, 2^m)
# LAT matrix shape: (2^m, 2^n)
```

Pass `output_bits=1..32` to either S-box helper to specify the codomain width.
For example, a constant four-entry table with `output_bits=3` has three coordinate
spectra and an LAT of shape `(4, 8)`. The default `output_bits=0` preserves legacy
inference from the largest table value. Every value must fit the chosen width.

### Performance Comparison: Backend Selection

```python
import numpy as np
import pyfwht as fwht
import time

def benchmark_backends(size, num_repeats=10, num_warmup=2):
    """Compare performance across different backends with statistical rigor."""
    data = np.random.randn(size).astype(np.float64)
    results = {}
    
    backends = [
        (fwht.Backend.CPU, "CPU (SIMD)"),
        (fwht.Backend.OPENMP, "OpenMP"),
    ]
    
    if fwht.has_gpu():
        backends.append((fwht.Backend.GPU, "GPU (CUDA)"))
    
    for backend, name in backends:
        timings = []
        
        # Warmup runs to stabilize cache and CPU frequency
        for _ in range(num_warmup):
            test_data = data.copy()
            fwht.fwht_f64_backend(test_data, backend)
        
        # Benchmark runs
        for _ in range(num_repeats):
            test_data = data.copy()
            start = time.perf_counter()
            fwht.fwht_f64_backend(test_data, backend)
            elapsed = time.perf_counter() - start
            timings.append(elapsed * 1000)  # Convert to ms
        
        # Statistical analysis
        timings_array = np.array(timings)
        mean_time = np.mean(timings_array)
        std_time = np.std(timings_array)
        median_time = np.median(timings_array)
        min_time = np.min(timings_array)
        
        # Use minimum time for throughput (best-case scenario, least noise)
        throughput = (size * fwht.log2(size)) / (min_time / 1000) / 1e9
        
        results[name] = {
            'mean': mean_time,
            'std': std_time,
            'median': median_time,
            'min': min_time,
            'throughput': throughput  # GOps/s based on minimum time
        }
    
    return results

# Test different sizes with sufficient repetitions
print("FWHT Performance Benchmark (Python)")
print("=" * 80)
print(f"Warmup runs: 2, Benchmark runs: 10 per configuration")
print(f"GPU available: {fwht.has_gpu()}")
print(f"OpenMP available: {fwht.has_openmp()}")
print(f"Version: {fwht.version()}")
print()

for k in range(20, 30, 2):
    size = 2**k
    print(f"\nSize: {size:,} (2^{k})")
    print("-" * 80)
    results = benchmark_backends(size, num_repeats=10, num_warmup=2)
    
    for name, metrics in results.items():
        print(f"  {name:15s}: {metrics['min']:7.2f} ms (min)  "
              f"{metrics['mean']:7.2f} ± {metrics['std']:5.2f} ms (mean±std)  "
              f"[{metrics['throughput']:5.2f} GOps/s]")
```

### Numerical Accuracy Validation

```python
import numpy as np
import pyfwht as fwht

def test_orthogonality(n):
    """
    Verify WHT orthogonality: WHT(WHT(x)) = n * x
    """
    x = np.random.randn(n)
    
    # Forward transform
    y = fwht.fwht_compute_f64(x)
    
    # Inverse transform (forward again, then divide by n)
    x_reconstructed = fwht.fwht_compute_f64(y) / n
    
    # Check reconstruction error
    error = np.linalg.norm(x - x_reconstructed)
    rel_error = error / np.linalg.norm(x)
    
    print(f"Size {n}: Relative error = {rel_error:.2e}")
    return rel_error < 1e-10

# Test for various sizes
for k in range(4, 16):
    assert test_orthogonality(2**k), f"Failed for size 2^{k}"

print("All orthogonality tests passed!")
```

## Performance & Precision Reference

Current benchmark tables live in [`bench/benchmarks.md`](../bench/benchmarks.md). The Python README focuses on installation and API usage. Consult the benchmark record whenever you need:

- GOps/s numbers for each backend or hardware platform
- GPU data-type comparisons (int32, fp64, fp32, fp16)
- The command, environment, and method behind each measurement

The benchmark sections below are older records, labelled with the pyfwht version that produced them.

## Benchmark Results

### Performance Comparison: CPU vs OpenMP vs GPU

Benchmark performed on GPU server with statistical rigor (10 runs per configuration, 2 warmup runs).

**System Configuration:**

- **GPU**: NVIDIA GeForce RTX 5090 (32 GB GDDR7)
- **CPU**: AMD EPYC 9334 32-Core Processor (64 threads with SMT)
- **System RAM**: 377 GB
- **CUDA**: Version 13.0 (driver 580.95.05, nvcc V13.0.88)
- **Library Version**: pyfwht 1.1.4

```
FWHT Performance Benchmark (Python)
================================================================================
Warmup runs: 2, Benchmark runs: 10 per configuration
GPU available: True
OpenMP available: True
Version: 1.1.4


Size: 1,048,576 (2^20)
--------------------------------------------------------------------------------
  CPU (SIMD)     :    4.11 ms (min)     4.15 ±  0.03 ms (mean±std)  [ 5.11 GOps/s]
  OpenMP         :    1.60 ms (min)    21.53 ± 31.49 ms (mean±std)  [13.09 GOps/s]
  GPU (CUDA)     :    0.86 ms (min)     0.87 ±  0.01 ms (mean±std)  [24.45 GOps/s]

Size: 4,194,304 (2^22)
--------------------------------------------------------------------------------
  CPU (SIMD)     :   20.78 ms (min)    21.50 ±  0.24 ms (mean±std)  [ 4.44 GOps/s]
  OpenMP         :    6.02 ms (min)    45.35 ± 38.26 ms (mean±std)  [15.32 GOps/s]
  GPU (CUDA)     :    3.55 ms (min)     3.58 ±  0.02 ms (mean±std)  [26.00 GOps/s]

Size: 16,777,216 (2^24)
--------------------------------------------------------------------------------
  CPU (SIMD)     :   90.52 ms (min)    90.68 ±  0.16 ms (mean±std)  [ 4.45 GOps/s]
  OpenMP         :   23.61 ms (min)    26.43 ±  2.96 ms (mean±std)  [17.06 GOps/s]
  GPU (CUDA)     :   16.32 ms (min)    16.35 ±  0.02 ms (mean±std)  [24.67 GOps/s]

Size: 67,108,864 (2^26)
--------------------------------------------------------------------------------
  CPU (SIMD)     :  447.80 ms (min)   448.15 ±  0.17 ms (mean±std)  [ 3.90 GOps/s]
  OpenMP         :  178.32 ms (min)   219.37 ± 19.93 ms (mean±std)  [ 9.78 GOps/s]
  GPU (CUDA)     :   66.09 ms (min)    66.15 ±  0.04 ms (mean±std)  [26.40 GOps/s]

Size: 268,435,456 (2^28)
--------------------------------------------------------------------------------
  CPU (SIMD)     : 2348.43 ms (min)  2350.81 ±  1.95 ms (mean±std)  [ 3.20 GOps/s]
  OpenMP         : 1178.15 ms (min)  1220.09 ± 26.66 ms (mean±std)  [ 6.38 GOps/s]
  GPU (CUDA)     :  268.10 ms (min)   268.44 ±  0.19 ms (mean±std)  [28.03 GOps/s]
```

**Key Observations:**

- **GPU Performance**: Achieves 24-28 GOps/s consistently, with extremely low variance (std < 0.2 ms even for large transforms)
- **RTX 5090 Advantage**: Latest generation GPU with GDDR7 memory provides excellent bandwidth for this memory-bound algorithm
- **OpenMP Scaling**: 2-4x speedup over single-threaded CPU on 32-core system
- **CPU SIMD**: Consistent ~4-5 GOps/s throughput with NEON/AVX2 optimizations
- **Speedup Summary**:
  - GPU vs CPU: **5.9x** for small sizes (2^20), up to **8.8x** for large sizes (2^28)
  - GPU vs OpenMP: **2.8x** for small sizes, up to **4.4x** for large sizes
- **Python Overhead**: Negligible - performance matches C library within measurement variance

**Run your own benchmark:** copy the `benchmark_backends` example from the Quick Start section above into a script and run it.

### Multi-Precision GPU Performance (fp64/fp32/fp16)

The pyfwht GPU backend now supports **multiple precision modes** for different speed/accuracy trade-offs. Benchmark on NVIDIA RTX 4090:

**System Configuration:**
- **GPU**: NVIDIA GeForce RTX 4090 (SM 8.9, 128 SMs, 24 GB GDDR6X)
- **CUDA**: Version 12.x
- **Library Version**: pyfwht 1.2.0+

#### Correctness Results (with precision-matched references)

```
Kernel               Max Error       Status              
-------------------------------------------------------
pyfwht fp64          0.00e+00        PASS               
pyfwht fp32          0.00e+00        PASS               
pyfwht fp16          1.25e-01        PASS               
```

Boolean ±1 test vectors match CPU exactly for fp32 and fp64, and for fp16 only when n ≤ 4096. The fp16 number above comes from a Gaussian floating-point workload (`benchmark_all_precisions_fixed.py`) and reflects intrinsic fp16 rounding.

#### Performance Results

**Single Transform (batch=1, dtype=float16):**

| Size | pyfwht GPU fp16 (ms / GOps/s) | Meta GPU fp16 (ms / GOps/s) | pyfwht Speedup |
|------|-------------------------------|-----------------------------|----------------|
|1024  | 0.032 ms / 0.64 GOps/s        | 0.051 ms / 0.40 GOps/s      | **1.6×**       |
|2048  | 0.034 ms / 1.31 GOps/s        | 0.054 ms / 0.84 GOps/s      | **1.6×**       |
|4096  | 0.036 ms / 2.76 GOps/s        | 0.049 ms / 2.02 GOps/s      | **1.4×**       |

**Batched Transforms (batch=100, dtype=float16):**

| Size | pyfwht GPU fp16 (ms / GOps/s) | Meta GPU fp16 (ms / GOps/s) | pyfwht Speedup |
|------|-------------------------------|-----------------------------|----------------|
|1024  | 0.030 ms / 68.01 GOps/s       | 0.049 ms / 41.65 GOps/s     | **1.6×**       |
|2048  | 0.030 ms / 148.59 GOps/s      | 0.049 ms / 91.59 GOps/s     | **1.6×**       |
|4096  | 0.031 ms / 314.83 GOps/s      | 0.049 ms / 199.43 GOps/s    | **1.6×**       |

**Key Highlights:**
- Tests run on NVIDIA RTX 4090 (driver 560.35.03, CUDA 12.6.85) using PyTorch tensors (zero-copy DLPack path).
- pyfwht beats Meta's CUDA kernel by 1.4–1.6× at every measured size and batch depth.
- Boolean workloads are bit-exact on fp16 only for n ≤ 4096; Gaussian floats exhibit max error ≈1.3e-1 (mean ≈2.5e-2, relative <6e-4).
- fp32 stays the balanced option (~1e-6 error) if you do not need fp16's throughput.
- Tensor Core kernels cover power-of-two sizes 256–32768; larger sizes fall back to the general CUDA backend.

**Usage Example:**

```python
import torch
from torch.utils.dlpack import to_dlpack
import pyfwht

# For maximum performance: use PyTorch tensors with DLPack (zero-copy)
data_fp64 = torch.randn(100, 4096, dtype=torch.float64, device='cuda')  # Max precision
data_fp32 = torch.randn(100, 4096, dtype=torch.float32, device='cuda')  # Balanced
data_fp16 = torch.randn(100, 4096, dtype=torch.float16, device='cuda')  # Max speed

# DLPack API (recommended): zero-copy, in-place, eliminates H2D/D2H overhead
# Arguments: DLPack capsule of a (batch_size, n) CUDA tensor, n, batch_size
pyfwht.gpu.batch_f64_dlpack(to_dlpack(data_fp64), 4096, 100)  # Uses fp64 kernel
pyfwht.gpu.batch_f32_dlpack(to_dlpack(data_fp32), 4096, 100)  # Uses fp32 kernel (balanced speed/accuracy)
pyfwht.gpu.batch_f16_dlpack(to_dlpack(data_fp16), 4096, 100)  # Uses fp16 kernel (maximum Tensor Core throughput)

# NumPy API (convenience): includes H2D/D2H transfers
import numpy as np
data_np = np.random.randn(100, 4096).astype(np.float16)
# fp16 data is passed as its raw uint16 bit pattern; the result is written back in place
pyfwht.gpu.batch_f16(data_np.view(np.uint16), 4096, 100)  # Transfers to GPU, computes, transfers back
```

**Performance Comparison:**
- **DLPack (PyTorch)**: Keeps tensors on the GPU (see tables above for up to 315 GOps/s at n=4096, batch=100)
- **NumPy**: Includes H2D/D2H transfers and is typically 10–100× slower for fp16 workloads
- **Recommendation**: Use DLPack for any high-throughput batch job; reserve NumPy for convenience scripts

**Run the multi-precision benchmark:**
```bash
cd python/tests
python benchmark_all_precisions_fixed.py
```

### FP16 precision and performance

For Boolean inputs in {-1, +1}, FP16 is exact for transform sizes up to 4096.
Above that size, representable values become more widely spaced, so coefficients
can round. General floating-point inputs can accumulate rounding error at every
size, and sufficiently large values can overflow. Use an integer transform with
an appropriate overflow bound when exact spectra are required.

The optimized FP16 path supports power-of-two sizes from 256 through 32768 on
compute capabilities 8.0 through 9.x. Other supported devices and sizes use
FP16-to-FP32 conversion, a transform, and conversion back to FP16. Conversion
uses round-to-nearest-even and preserves representable subnormal values.

Measure throughput with representative inputs on the target GPU. Device-resident
DLPack calls avoid host transfers; NumPy calls include those transfers. Kernel-only
and end-to-end measurements answer different questions and should be compared
separately. The library does not promise a fixed speedup or error percentage.

The default library produces no precision warning. With `FWHT_LOG_DISPATCH=1`,
it prints an FP16 diagnostic once per calling thread. The optional
`FWHT_SILENCE_FP16_WARNING=1` setting suppresses that diagnostic.

## Examples

The `examples/` directory contains comprehensive demonstrations:

- **`basic_usage.py`** - Core API: transforms, backends, Boolean functions, utilities
- **`boolean_packed.py`** - Bit-packed Boolean WHT for memory-efficient cryptanalysis
- **`gpu_batch.py`** - GPU batch transforms, profiling, and persistent contexts
- **`gpu_multi_precision.py`** - fp16/fp32/fp64 with PyTorch DLPack integration
- **`compare_fast_hadamard.py`** - Benchmarks vs. Dao-AILab's fast-hadamard-transform
- **`sbox_analysis.py`** - S-box cryptanalysis with LAT computation (includes 16-bit GPU example)

Run any example:
```bash
cd examples
python basic_usage.py
python sbox_analysis.py  # Shows AES S-box analysis, LAT computation, and 16-bit GPU demo
```

## Development

### Running Tests

The `tests/` directory contains comprehensive Python test suites and benchmarks:

```bash
# Install package in development mode
pip install -e .

# Install testing dependencies
pip install pytest pytest-cov

# Run all tests
pytest tests/ -v

# Run with coverage report
pytest tests/ --cov=pyfwht --cov-report=html

# Run specific test files
pytest tests/test_correctness.py -v          # Core correctness tests
pytest tests/test_gpu.py -v                  # GPU tests (requires CUDA)

# Run benchmarks (not part of pytest suite)
python tests/benchmark_all_precisions_fixed.py     # Multi-precision GPU benchmarks
python tests/benchmark_compare_meta.py             # Compare vs Dao-AILab implementation
```

**Available test files:**
- `test_correctness.py` - Core API validation (transforms, Boolean functions, backends, batch processing)
- `test_gpu.py` - GPU-specific tests (Tensor Cores, fp16/fp32/fp64, batch operations, DLPack)
- `benchmark_all_precisions_fixed.py` - Multi-precision performance benchmarks
- `benchmark_compare_meta.py` - Comparative benchmarks against fast-hadamard-transform (Dao-AILab), or Meta's kernel with `--meta-module faster_hadamard_transform`

**GPU Tests:** Tests in `test_gpu.py` automatically skip if CUDA is not available. Build with `USE_CUDA=1 pip install -e .` to enable GPU support.

For GPU release validation, run `FWHT_TEST_REQUIRE_GPU=1 python -m pytest tests/ -q -rs`.
This requires a CUDA-enabled extension, a visible device, and CuPy for the DLPack
ownership tests in `test_gpu_contracts.py`. Tests requiring two GPUs can still
skip on a single-GPU allocation; review the reported skip reasons.

On an offline Linux GPU node, first copy the Python source and a directory of
wheels matching its Python version and architecture. From this `python/`
directory, with the CUDA toolkit loaded and a virtual environment activated:

```bash
python -m pip install --no-index --find-links=/path/to/wheels \
  setuptools wheel pybind11 numpy pytest cupy-cuda12x
USE_CUDA=1 python -m pip install --no-index --no-build-isolation --no-deps .
FWHT_TEST_REQUIRE_GPU=1 python -m pytest tests/ -q -rs
```

The example assumes CUDA 12.x. The wheel directory must also contain dependency
wheels; the Mac extension binary cannot be used on the Linux server.

### Building Distribution Packages

```bash
pip install build
python -m build  # Creates both sdist and wheel in dist/
```

## Relation to C Library

This package wraps the [libfwht](../README.md) C library. All computation happens in highly-optimized C/CUDA code; Python provides only a thin interface layer.

For C/C++ projects, use the C library directly. For Python workflows, this package provides seamless NumPy integration.

## License

GNU General Public License v3.0 or later (GPL-3.0-or-later)

See [LICENSE](../LICENSE) file for full text.

## Citation

If you use this library in your research, please cite:

```bibtex
@software{libfwht,
  author = {Hadipour, Hosein},
  title = {libfwht: Fast Walsh-Hadamard Transform Library},
  year = {2025},
  url = {https://github.com/hadipourh/fwht}
}
```

## Support

- **Issues**: https://github.com/hadipourh/fwht/issues
- **Email**: hsn.hadipour@gmail.com
- **Documentation**: https://github.com/hadipourh/fwht

## Contributing

Contributions welcome! Please open an issue or pull request on GitHub.
