mirror of
https://github.com/paboyle/Grid.git
synced 2026-10-25 23:23:19 +00:00
Compare commits
95
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01c3189d17 | ||
|
|
f1249685aa | ||
|
|
722d68b0d9 | ||
|
|
c1284e080a | ||
|
|
d2189d59e0 | ||
|
|
e862dd662b | ||
|
|
42ff77cec8 | ||
|
|
d11ad4d2f0 | ||
|
|
9ebf2fec79 | ||
|
|
ab0d6d3706 | ||
|
|
4aa96a16c5 | ||
|
|
bb99123e6d | ||
|
|
9e8cba3944 | ||
|
|
d5cab295b2 | ||
|
|
5a67f0602c | ||
|
|
d57c49d73d | ||
|
|
5754c965d5 | ||
|
|
64ee6e90c9 | ||
|
|
7752e7ead1 | ||
|
|
f14be5e331 | ||
|
|
5a77a4a052 | ||
|
|
83b752bdd3 | ||
|
|
34a6ba3475 | ||
|
|
819f706778 | ||
|
|
3b28e3c98f | ||
|
|
a696953485 | ||
|
|
aecc50869c | ||
|
|
99be36c891 | ||
|
|
af1fb41d55 | ||
|
|
b4c77ca762 | ||
|
|
82a8f1342e | ||
|
|
d4b685cf2d | ||
|
|
84707cc3a8 | ||
|
|
88ea24687f | ||
|
|
167f94e86c | ||
|
|
09aa843984 | ||
|
|
24752002fa | ||
|
|
f3223021fd | ||
|
|
4e1d95d3bb | ||
|
|
2ed38f63ca | ||
|
|
80d2a8d88d | ||
|
|
2ac5431401 | ||
|
|
3e71cac7ae | ||
|
|
e8e7ef08fc | ||
|
|
5c00fe6bef | ||
|
|
3175788f97 | ||
|
|
6f1788bb38 | ||
|
|
dcda74f924 | ||
|
|
df4c2a082b | ||
|
|
88611659a3 | ||
|
|
504b85dfc0 | ||
|
|
43ea83e5e1 | ||
|
|
376150c3df | ||
|
|
842e0391e7 | ||
|
|
17e3799bcc | ||
|
|
985ab70f85 | ||
|
|
1e85081986 | ||
|
|
3876fe5a29 | ||
|
|
6692425aa2 | ||
|
|
d5ac4fc67f | ||
|
|
3538faf449 | ||
|
|
0b457b9d52 | ||
|
|
fe0ab5f1a9 | ||
|
|
caa66418bd | ||
|
|
786496f22e | ||
|
|
68af1bba67 | ||
|
|
bf2a715ef7 | ||
|
|
4042ebf1bf | ||
|
|
82f35001ff | ||
|
|
fa30c791aa | ||
|
|
612049f1dd | ||
|
|
0b92ef990c | ||
|
|
82d411ca7b | ||
|
|
597086a031 | ||
|
|
b210ddf9a7 | ||
|
|
c5d02e5799 | ||
|
|
9dcd7ca761 | ||
|
|
c1e5ef9476 | ||
|
|
6fd71aea9d | ||
|
|
a18b0d496c | ||
|
|
19f0737b98 | ||
|
|
16d3c9cf75 | ||
|
|
3b9fc72451 | ||
|
|
99644f5d0a | ||
|
|
7780d88d26 | ||
|
|
2bf9179d2c | ||
|
|
c606f5dca0 | ||
|
|
632f5916c7 | ||
|
|
9057694895 | ||
|
|
5e85aef19d | ||
|
|
2b6d40c7e1 | ||
|
|
33b80c4e8e | ||
|
|
8419cc5c64 | ||
|
|
2cc6deb8e0 | ||
|
|
19d0590579 |
No files matched your search
@@ -1,183 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## What This Is
|
||||
|
||||
Grid is a data-parallel C++ library for lattice QCD. It provides SIMD-vectorised lattice containers, MPI-based domain decomposition, GPU acceleration (CUDA/HIP/SYCL), and a full suite of QCD algorithms including HMC.
|
||||
|
||||
## Build
|
||||
|
||||
Uses GNU Autotools. The bootstrap step only needs to run once (or after `configure.ac` changes).
|
||||
|
||||
```bash
|
||||
./bootstrap.sh # downloads Eigen 3.4.0, generates configure
|
||||
mkdir build && cd build
|
||||
../configure [options]
|
||||
make -j$(nproc)
|
||||
make check # run root-level tests
|
||||
make install
|
||||
```
|
||||
|
||||
Key configure options:
|
||||
|
||||
| Option | Common values |
|
||||
|--------|---------------|
|
||||
| `--enable-simd=` | `AVX2`, `AVX512`, `KNL`, `A64FX`, `NEONv8`, `GPU` |
|
||||
| `--enable-comms=` | `mpi-auto`, `mpi3-auto`, `none` |
|
||||
| `--enable-accelerator=` | `cuda`, `hip`, `sycl` |
|
||||
| `--enable-shm=` | `shmopen`, `hugetlbfs`, `nvlink` |
|
||||
| `--enable-Nc=` | `3` (default), `2`, `4`, `5` |
|
||||
| `--with-gmp=`, `--with-mpfr=`, `--with-fftw=`, `--with-lime=` | paths to libs |
|
||||
| `--enable-hdf5`, `--enable-mkl`, `--enable-lapack` | optional features |
|
||||
|
||||
GPU builds additionally need `--enable-gen-simd-width=64` (sets 512-bit SIMD width for GPU warp/wavefront sizing) and `--enable-unified=no --enable-shm=nvlink` for multi-GPU runs.
|
||||
|
||||
To speed up compilation, `--disable-fermion-reps --disable-gparity` skips instantiating G-parity and higher-representation fermion operators.
|
||||
|
||||
Platform recipes from `README.md`:
|
||||
- **KNL**: `--enable-simd=KNL --enable-comms=mpi3-auto --enable-mkl`
|
||||
- **Skylake/Haswell**: `--enable-simd=AVX512` or `AVX2` + `--enable-comms=mpi3-auto`
|
||||
- **AMD EPYC**: `--enable-simd=AVX2 --enable-comms=mpi3`
|
||||
- **A64FX (Fugaku)**: `--enable-simd=A64FX --enable-comms=mpi3 --enable-shm=shmget` (see `SVE_README.txt`)
|
||||
|
||||
Complete, working `configure` invocations for specific HPC systems (Frontier/ROCm, Perlmutter/CUDA, Summit, SDCC-A100, etc.) live in `systems/<platform>/config-command`. These are the canonical references for production builds.
|
||||
|
||||
Required external libs: GMP, MPFR, OpenSSL, zlib.
|
||||
|
||||
### Use `systems/` for real machines
|
||||
|
||||
`systems/<machine>/` holds the known-good build for each production platform (`Frontier`, `Aurora`, `Perlmutter`, `Summit`, `Tursa`, `Lumi`, `Booster`, `Crusher`, `SDCC-*`, `mac-arm`, …). Each contains a `config-command` (the exact `../../configure` invocation) and a `sourceme.sh` (module loads and env). **Prefer copying/adapting these over hand-rolling configure flags** — they encode compiler workarounds, `LDFLAGS`, and shared-memory settings that are easy to get wrong. `systems/WorkArounds.txt` records known vendor bugs.
|
||||
|
||||
Note the GPU builds use `--enable-simd=GPU --enable-gen-simd-width=64`, so `Nsimd` is *not* 1 on device (it is `64/sizeof(scalar)`).
|
||||
|
||||
### Regenerating `Make.inc` — required after adding or deleting source files
|
||||
|
||||
`Make.inc` files are generated, not tracked in git (`.gitignore`d). `scripts/filelist` walks `Grid/`, `tests/*`, `benchmarks/`, `examples/`, and `HMC/` and writes the file lists and per-test `bin_PROGRAMS` rules. Every new `.cc`/`.h` in `Grid/`, and every new `Test_*.cc` / `Benchmark_*.cc` / `Example_*.cc`, is invisible to the build until you run:
|
||||
|
||||
```bash
|
||||
./scripts/filelist # from the source root, then re-run configure/make
|
||||
```
|
||||
|
||||
`bootstrap.sh` runs it for you on the first setup.
|
||||
|
||||
## Running Tests and Benchmarks
|
||||
|
||||
```bash
|
||||
# From build directory
|
||||
make check # root-level tests (Test_simd, Test_cshift, etc.)
|
||||
make -C tests/<subdir> tests # build tests in a subdirectory
|
||||
make tests # build all tests across all subdirectories
|
||||
./tests/core/Test_simd # run a single test binary directly
|
||||
mpirun -n 4 ./tests/core/Test_cshift --grid 16.16.16.16 --mpi 1.1.1.4
|
||||
```
|
||||
|
||||
`make check` is a thin smoke test — building a subdirectory with `make -C tests/<subdir> tests` and running the relevant binaries directly is the normal development loop. Test binaries take Grid's standard command-line arguments (`--grid`, `--mpi`, `--accelerator-threads`, `--threads`, `--debug-signals`, `--log`); see `Grid/util/Init.cc`.
|
||||
|
||||
Test subdirectories and their focus: `core` (SIMD, stencil, comms), `solver` (CG, GMRES, eigensolvers), `hmc` (MD integrators), `forces` (fermion forces), `lanczos`, `IO`, `smearing`, `sp2n`, `debug`.
|
||||
|
||||
Tests and benchmarks that need optional fermion representations are guarded by `disable_tests_without_instantiations.h` / `disable_benchmarks_without_instantiations.h`, so a `--disable-fermion-reps --disable-gparity` build silently compiles them to no-ops.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Layer stack (bottom to top)
|
||||
|
||||
1. **SIMD layer** (`Grid/simd/`) — platform-specific intrinsics wrapped into `vRealF`, `vComplexD`, etc. The SIMD width and layout are compile-time constants controlled by `--enable-simd`.
|
||||
|
||||
2. **Tensor layer** (`Grid/tensors/`) — Lorentz/colour/spin tensor algebra built on top of SIMD types. `iMatrix`, `iVector`, `iScalar` templates compose into QCD types like `ColourMatrix`, `SpinColourVector`.
|
||||
|
||||
3. **Lattice layer** (`Grid/lattice/`) — `Lattice<T>` container: a site-local tensor replicated across a distributed Cartesian grid. All arithmetic is site-parallel and expression-template-fused.
|
||||
|
||||
4. **Cartesian/comms layer** (`Grid/cartesian/`, `Grid/communicator/`) — `GridCartesian` holds the MPI topology and local/global geometry. `Grid/cshift/` implements nearest-neighbour halo exchange; `Grid/stencil/` is the optimised multi-hop stencil used by Dirac operators.
|
||||
|
||||
5. **Algorithm layer** (`Grid/algorithms/`) — iterative solvers (CG, GMRES, BiCGSTAB, mixed-precision), eigensolvers (Lanczos, LAPACK), FFT, smearing, and multigrid.
|
||||
|
||||
6. **QCD layer** (`Grid/qcd/`) — gauge and fermion actions, HMC integrators, observables.
|
||||
|
||||
### QCD subsystem (`Grid/qcd/`)
|
||||
|
||||
- `action/fermion/` — Wilson, Clover, DWF (Mobius), Staggered, twisted-mass, G-parity variants
|
||||
- `action/gauge/` — Wilson gauge, Symanzik, Iwasaki, DBW2, plaquette+rect
|
||||
- `representations/` — Fundamental, Adjoint, Two-index, Sp(2n)
|
||||
- `hmc/` — Leapfrog, OMF2/OMF4 integrators; pseudofermion refreshment; Metropolis accept/reject
|
||||
- `smearing/` — APE, Stout, HEX, gradient flow
|
||||
- `observables/` — Polyakov loop, plaquette, topological charge
|
||||
|
||||
### GPU acceleration and the view/memory-manager discipline
|
||||
### Multigrid (`Grid/algorithms/multigrid/`)
|
||||
|
||||
Aggregation-based algebraic multigrid for Wilson-type fermions. Key files: `CoarsenedMatrix.h` (coarse operator), `GeneralCoarsenedMatrix.h` and `GeneralCoarsenedMatrixMultiRHS.h` (general coarsening supporting multi-RHS solves), `Aggregates.h` (near-null vector construction), `Geometry.h` (coarse-grid geometry). `MultiGrid.h` is the top-level include.
|
||||
|
||||
### GPU acceleration
|
||||
|
||||
GPU support is injected via macros in `Grid/threads/Accelerator.h` — `accelerator_for(i, n, nsimd, {...})`, `accelerator_forNB` (non-blocking, must be followed by `accelerator_barrier()`), `accelerator_for2dNB`, and `accelerator_inline`. On a CPU build these degrade to `thread_for` (OpenMP). Unified virtual memory is on by default (`--enable-unified=yes`); device-aware MPI (`--enable-accelerator-aware-mpi`) avoids device→host copies on transfers.
|
||||
|
||||
Lattice data is **not** directly addressable inside a kernel. You must open a view with the correct access mode so `Grid/allocator/MemoryManager.h` can move/mark the data:
|
||||
|
||||
```cpp
|
||||
autoView(out_v, out, AcceleratorWriteDiscard); // RAII; closes at end of scope
|
||||
autoView(in_v, in, AcceleratorRead);
|
||||
accelerator_for(ss, grid->oSites(), Nsimd, {
|
||||
coalescedWrite(out_v[ss], coalescedRead(in_v[ss]));
|
||||
});
|
||||
```
|
||||
|
||||
Modes are `AcceleratorRead/Write/WriteDiscard` and `CpuRead/Write/WriteDiscard`. Getting the mode wrong (e.g. `AcceleratorRead` on a field you write) produces stale-data bugs that only appear on GPU builds. Inside kernels use `coalescedRead`/`coalescedWrite` rather than raw `operator[]` — they map the SIMD lane onto `threadIdx.x` so accesses stay coalesced.
|
||||
|
||||
### Repo-local debugging skills (`skills/`)
|
||||
|
||||
`skills/` contains hard-won, Grid-specific playbooks written as invocable skill files. Consult them before debugging in these areas rather than reasoning from first principles:
|
||||
|
||||
| File | Covers |
|
||||
|---|---|
|
||||
| `gpu-memory-performance.md` | `acceleratorThreads()`, LambdaApply thread mapping, `coalescedRead` idiom, fused vs staged HBM access |
|
||||
| `gpu-runtime-correctness.md` | GPU runtime returning early from sync, silent wrong answers |
|
||||
| `communication-overlap.md` | 7-phase halo pipeline, per-packet events, host-staging vs GPU-direct RDMA |
|
||||
| `mpi-heterogeneous.md` | `MPI_Sendrecv` device-buffer aliasing, deterministic reductions |
|
||||
| `compiler-validation.md` | Isolating GPU compiler codegen bugs, minimal reproducers |
|
||||
| `correctness-verification.md` | Double-run fingerprinting, per-packet checksums, flight recorder |
|
||||
| `hang-diagnosis.md` | Diagnosing MPI/accelerator hangs |
|
||||
|
||||
The key loop macros (defined in `Grid/threads/Accelerator.h`) are:
|
||||
- `accelerator_for(iter, num, nsimd, {...})` — maps to CUDA/HIP kernel or OpenMP loop; `nsimd` is the innermost SIMD lane count
|
||||
- `accelerator_forNB(...)` — non-blocking variant (no implicit barrier)
|
||||
- `accelerator_for2dNB(iter1, num1, iter2, num2, nsimd, {...})` — 2D kernel launch
|
||||
- `thread_for(iter, num, {...})` — CPU OpenMP loop (never dispatches to GPU)
|
||||
|
||||
On CPU builds, `accelerator_for` aliases to `thread_for`.
|
||||
|
||||
### Solver patterns
|
||||
|
||||
`SchurRedBlack` (`Grid/algorithms/iterative/SchurRedBlack.h`) implements red-black (even/odd) preconditioning for fermion operators. Most production fermion solves use `SchurRedBlackDiagMooeeSolve` or similar wrappers that internally call a `ConjugateGradient` on the Schur complement.
|
||||
|
||||
Mixed-precision solvers (`ConjugateGradientMixedPrec`, `BiCGSTABMixedPrec`) drive a double-precision outer loop with single-precision inner solves.
|
||||
|
||||
### Memory and I/O
|
||||
|
||||
- `Grid/allocator/` — aligned/NUMA-aware allocators; caching allocator via `--enable-alloc-cache`
|
||||
- `Grid/parallelIO/` — distributed parallel reader/writer for ILDG (via LIME), SciDAC, and native binary formats
|
||||
- `Grid/serialisation/` — text, binary, HDF5, XML/JSON serialisation of arbitrary Grid objects
|
||||
|
||||
### Executables
|
||||
|
||||
- `HMC/` — production HMC driver programmes (e.g. `Mobius2p1f.cc`, `DWF_plus_DSDR_nf2plus1_Shamir_Gparity.cc`)
|
||||
- `benchmarks/` — `Benchmark_dwf`, `Benchmark_ITT`, `Benchmark_comms`, `Benchmark_memory_bandwidth`, … used to qualify a new machine
|
||||
- `examples/` — small, readable programmes (`Example_plaquette.cc`, `Example_Mobius_spectrum.cc`) that are the best starting point for learning the API
|
||||
|
||||
Each of these directories auto-builds every top-level `.cc` as its own binary via `scripts/filelist`.
|
||||
|
||||
Every programme is wrapped in `Grid_init(&argc, &argv)` / `Grid_finalize()` (`Grid/util/Init.h`).
|
||||
|
||||
## Key Conventions
|
||||
|
||||
- **C++17** is required throughout.
|
||||
- Template structure: most classes are templated on `<_FImpl>` (fermion impl) or `<Gimpl>` (gauge impl), which encode the representation and precision. Instantiation is controlled by `--enable-fermion-instantiations`.
|
||||
- **Tensor indices are positional, not labelled.** The `Grid/tensors/` arithmetic recurses structurally over the `iScalar`/`iVector`/`iMatrix` nest: each level defines only the {scalar,vector,matrix}² products at its own level, with element types resolved by automatic type deduction, so every colour/spin/lorentz combination composes from ~200 lines (versus the pre-C++11 QDP++/PETE approach of machine-generating every case). An index's meaning derives entirely from its nesting depth counted from the outside; `iScalar` is the identity/broadcast case at every level. Never insert or remove a nesting level casually — the multiplication tables contract by position.
|
||||
- **Multigrid coarsening deepens the tensor nest by one level.** A coarse site vector is `iVector<CComplex,nbasis>`, and `innerProduct` on it returns `iScalar<CComplex>` — one level deeper than the fine block scalar. So the block-inner-product scalar type gains one `iScalar` wrapper per MG level (fine: `vTComplex`; level 2: `iScalar<vTComplex>`; see `examples/Example_pvdagm_3level.cc`). When calling `blockInnerProduct`/`blockZAXPY`/`blockOrthogonalise` on coarse fields, the coarse scalar type must match `decltype(innerProduct(siteVector(),siteVector()))` exactly; a wrong depth fails to compile (no viable `operator=` deep in the instantiation chain) rather than mis-contracting.
|
||||
- The `RealD`/`RealF`/`ComplexD`/`ComplexF` typedefs are used everywhere; avoid raw `double`/`float`.
|
||||
- Use `GRID_ASSERT(cond)` (defined in `Grid/GridStd.h`), not bare `assert` — it prints a Grid-formatted message and aborts cleanly under MPI.
|
||||
- Logging is stream-based, not macro-based: `std::cout << GridLogMessage << ... << std::endl;`. Channels declared in `Grid/log/Log.h` include `GridLogError`, `GridLogWarning`, `GridLogDebug`, `GridLogPerformance`, `GridLogIterative`, `GridLogSolver`, `GridLogHMC`, `GridLogComms`, `GridLogMemory`, `GridLogDslash`, `GridLogIRL`, `GridLogMG`. A subset is switched on at runtime with e.g. `--log Error,Warning,Message,Performance,Iterative,Integrator,Debug,Colours` (names given without the `GridLog` prefix).
|
||||
- Performance-critical paths use `GRID_TRACE(name)` from `Grid/perfmon/Tracing.h` (compiled out unless `--enable-tracing` selects a backend) and the `GridStopWatch` timers in `Grid/perfmon/Timer.h`.
|
||||
- Reductions across MPI ranks go through `GridBase::GlobalSum` / `GlobalMax`; never reduce with bare MPI calls inside library code.
|
||||
- Everything lives in `NAMESPACE_BEGIN(Grid)` / `NAMESPACE_END(Grid)` macros; follow the surrounding file rather than writing `namespace Grid { }`.
|
||||
- British spelling is used in identifiers and comments (`colour`, `neighbour`, `serialisation`).
|
||||
@@ -55,6 +55,7 @@ NAMESPACE_CHECK(approx);
|
||||
#include <Grid/algorithms/blas/MomentumProject.h>
|
||||
NAMESPACE_CHECK(deflation);
|
||||
#include <Grid/algorithms/iterative/ConjugateGradient.h>
|
||||
//#include <Grid/algorithms/iterative/EigCG.h>
|
||||
NAMESPACE_CHECK(ConjGrad);
|
||||
#include <Grid/algorithms/iterative/BiCGSTAB.h>
|
||||
NAMESPACE_CHECK(BiCGSTAB);
|
||||
@@ -75,6 +76,7 @@ NAMESPACE_CHECK(BiCGSTAB);
|
||||
#include <Grid/algorithms/iterative/FlexibleCommunicationAvoidingGeneralisedMinimalResidual.h>
|
||||
#include <Grid/algorithms/iterative/MixedPrecisionFlexibleGeneralisedMinimalResidual.h>
|
||||
#include <Grid/algorithms/iterative/ImplicitlyRestartedLanczos.h>
|
||||
#include <Grid/algorithms/iterative/SimpleLanczos.h>
|
||||
#include <Grid/algorithms/iterative/PowerMethod.h>
|
||||
#include <Grid/algorithms/iterative/AdefGeneric.h>
|
||||
#include <Grid/algorithms/iterative/AdefMrhs.h>
|
||||
@@ -83,4 +85,17 @@ NAMESPACE_CHECK(PowerMethod);
|
||||
NAMESPACE_CHECK(multigrid);
|
||||
#include <Grid/algorithms/FFT.h>
|
||||
|
||||
#include <Grid/algorithms/iterative/KrylovSchur.h>
|
||||
#include <Grid/algorithms/iterative/BlockKrylovSchur.h>
|
||||
#include <Grid/algorithms/iterative/SplitGridBlockKrylovSchur.h>
|
||||
#include <Grid/algorithms/iterative/HarmonicBlockKrylovSchur.h>
|
||||
#include <Grid/algorithms/iterative/TrueHarmonicBlockKrylovSchur.h>
|
||||
#include <Grid/algorithms/iterative/Gamma5BlockLanczos.h>
|
||||
//#include <Grid/algorithms/iterative/Gamma5ScalarLanczos.h>
|
||||
#include <Grid/algorithms/iterative/Arnoldi.h>
|
||||
#include <Grid/algorithms/iterative/LanczosBidiagonalization.h>
|
||||
#include <Grid/algorithms/iterative/RestartedLanczosBidiagonalization.h>
|
||||
//#include <Grid/algorithms/iterative/GCR.h>
|
||||
#include <Grid/algorithms/iterative/MultiSplittingPreconditionedCG.h>
|
||||
|
||||
#endif
|
||||
+306
-303
@@ -1,6 +1,6 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/Cshift.h
|
||||
|
||||
@@ -65,16 +65,17 @@ public:
|
||||
typedef hipfftDoubleComplex FFTW_scalar;
|
||||
typedef hipfftHandle FFTW_plan;
|
||||
static FFTW_plan fftw_plan_many_dft(int rank, int *n,int howmany,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
int sign, unsigned flags) {
|
||||
FFTW_plan p;
|
||||
auto rv = hipfftPlanMany(&p,rank,n,n,istride,idist,n,ostride,odist,HIPFFT_Z2Z,howmany);
|
||||
GRID_ASSERT(rv==HIPFFT_SUCCESS);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
inline static void fftw_execute_dft(const FFTW_plan p,FFTW_scalar *in,FFTW_scalar *out, int sign) {
|
||||
hipfftResult rv;
|
||||
if ( sign == forward ) rv =hipfftExecZ2Z(p,in,out,HIPFFT_FORWARD);
|
||||
@@ -82,25 +83,29 @@ public:
|
||||
accelerator_barrier();
|
||||
GRID_ASSERT(rv==HIPFFT_SUCCESS);
|
||||
}
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) { hipfftDestroy(p); }
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) {
|
||||
hipfftDestroy(p);
|
||||
}
|
||||
};
|
||||
template<> struct FFTW<ComplexF> {
|
||||
public:
|
||||
static const int forward=FFTW_FORWARD;
|
||||
static const int backward=FFTW_BACKWARD;
|
||||
typedef hipfftComplex FFTW_scalar;
|
||||
typedef hipfftHandle FFTW_plan;
|
||||
typedef hipfftComplex FFTW_scalar;
|
||||
typedef hipfftHandle FFTW_plan;
|
||||
|
||||
static FFTW_plan fftw_plan_many_dft(int rank, int *n,int howmany,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
int sign, unsigned flags) {
|
||||
FFTW_plan p;
|
||||
auto rv = hipfftPlanMany(&p,rank,n,n,istride,idist,n,ostride,odist,HIPFFT_C2C,howmany);
|
||||
GRID_ASSERT(rv==HIPFFT_SUCCESS);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
inline static void fftw_execute_dft(const FFTW_plan p,FFTW_scalar *in,FFTW_scalar *out, int sign) {
|
||||
hipfftResult rv;
|
||||
if ( sign == forward ) rv =hipfftExecC2C(p,in,out,HIPFFT_FORWARD);
|
||||
@@ -108,7 +113,9 @@ public:
|
||||
accelerator_barrier();
|
||||
GRID_ASSERT(rv==HIPFFT_SUCCESS);
|
||||
}
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) { hipfftDestroy(p); }
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) {
|
||||
hipfftDestroy(p);
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
@@ -119,45 +126,53 @@ public:
|
||||
static const int backward=FFTW_BACKWARD;
|
||||
typedef cufftDoubleComplex FFTW_scalar;
|
||||
typedef cufftHandle FFTW_plan;
|
||||
|
||||
static FFTW_plan fftw_plan_many_dft(int rank, int *n,int howmany,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
int sign, unsigned flags) {
|
||||
FFTW_plan p;
|
||||
cufftPlanMany(&p,rank,n,n,istride,idist,n,ostride,odist,CUFFT_Z2Z,howmany);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
inline static void fftw_execute_dft(const FFTW_plan p,FFTW_scalar *in,FFTW_scalar *out, int sign) {
|
||||
if ( sign == forward ) cufftExecZ2Z(p,in,out,CUFFT_FORWARD);
|
||||
else cufftExecZ2Z(p,in,out,CUFFT_INVERSE);
|
||||
accelerator_barrier();
|
||||
}
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) { cufftDestroy(p); }
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) {
|
||||
cufftDestroy(p);
|
||||
}
|
||||
};
|
||||
template<> struct FFTW<ComplexF> {
|
||||
public:
|
||||
static const int forward=FFTW_FORWARD;
|
||||
static const int backward=FFTW_BACKWARD;
|
||||
typedef cufftComplex FFTW_scalar;
|
||||
typedef cufftHandle FFTW_plan;
|
||||
typedef cufftHandle FFTW_plan;
|
||||
|
||||
static FFTW_plan fftw_plan_many_dft(int rank, int *n,int howmany,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
int sign, unsigned flags) {
|
||||
FFTW_plan p;
|
||||
cufftPlanMany(&p,rank,n,n,istride,idist,n,ostride,odist,CUFFT_C2C,howmany);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
inline static void fftw_execute_dft(const FFTW_plan p,FFTW_scalar *in,FFTW_scalar *out, int sign) {
|
||||
if ( sign == forward ) cufftExecC2C(p,in,out,CUFFT_FORWARD);
|
||||
else cufftExecC2C(p,in,out,CUFFT_INVERSE);
|
||||
accelerator_barrier();
|
||||
}
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) { cufftDestroy(p); }
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) {
|
||||
cufftDestroy(p);
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
@@ -168,325 +183,313 @@ public:
|
||||
typedef fftw_complex FFTW_scalar;
|
||||
typedef fftw_plan FFTW_plan;
|
||||
static FFTW_plan fftw_plan_many_dft(int rank, int *n,int howmany,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
int sign, unsigned flags) {
|
||||
return ::fftw_plan_many_dft(rank,n,howmany,in,inembed,istride,idist,out,onembed,ostride,odist,sign,flags);
|
||||
}
|
||||
}
|
||||
|
||||
inline static void fftw_execute_dft(const FFTW_plan p,FFTW_scalar *in,FFTW_scalar *out, int sign) {
|
||||
::fftw_execute_dft(p,in,out);
|
||||
}
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) { ::fftw_destroy_plan(p); }
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) {
|
||||
::fftw_destroy_plan(p);
|
||||
}
|
||||
};
|
||||
template<> struct FFTW<ComplexF> {
|
||||
public:
|
||||
typedef fftwf_complex FFTW_scalar;
|
||||
typedef fftwf_plan FFTW_plan;
|
||||
static FFTW_plan fftw_plan_many_dft(int rank, int *n,int howmany,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
FFTW_scalar *in, int *inembed,
|
||||
int istride, int idist,
|
||||
FFTW_scalar *out, int *onembed,
|
||||
int ostride, int odist,
|
||||
int sign, unsigned flags) {
|
||||
return ::fftwf_plan_many_dft(rank,n,howmany,in,inembed,istride,idist,out,onembed,ostride,odist,sign,flags);
|
||||
}
|
||||
}
|
||||
|
||||
inline static void fftw_execute_dft(const FFTW_plan p,FFTW_scalar *in,FFTW_scalar *out, int sign) {
|
||||
::fftwf_execute_dft(p,in,out);
|
||||
}
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) { ::fftwf_destroy_plan(p); }
|
||||
inline static void fftw_destroy_plan(const FFTW_plan p) {
|
||||
::fftwf_destroy_plan(p);
|
||||
}
|
||||
};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
struct FFTbase {
|
||||
double flops;
|
||||
double flops_call;
|
||||
uint64_t usec;
|
||||
GridCartesian *_grid;
|
||||
|
||||
static const int forward = FFTW_FORWARD;
|
||||
static const int backward = FFTW_BACKWARD;
|
||||
|
||||
double Flops(void) { return flops; }
|
||||
double MFlops(void) { return flops / usec; }
|
||||
double USec(void) { return (double)usec; }
|
||||
|
||||
FFTbase(GridCartesian *grid) : _grid(grid), flops(0), flops_call(0), usec(0) {}
|
||||
};
|
||||
|
||||
// Barrel-shift gather, FFT execute, and insert. Called by both FFT and PlannedFFT.
|
||||
// The caller is responsible for plan acquisition and destruction.
|
||||
template<class vobj>
|
||||
static void FFT_dim_execute(
|
||||
Lattice<vobj> &result,
|
||||
const Lattice<vobj> &source,
|
||||
int dim, int sign,
|
||||
typename FFTW<typename vobj::scalar_type>::FFTW_plan p,
|
||||
GridCartesian *grid,
|
||||
double &flops, double &flops_call, uint64_t &usec)
|
||||
{
|
||||
typedef typename vobj::scalar_type scalar;
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
typedef typename vobj::scalar_type scalar_type;
|
||||
typedef typename vobj::vector_type vector_type;
|
||||
typedef typename FFTW<scalar>::FFTW_scalar FFTW_scalar;
|
||||
|
||||
const int Ndim = grid->Nd();
|
||||
int L = grid->_ldimensions[dim];
|
||||
int G = grid->_fdimensions[dim];
|
||||
int Ncomp = sizeof(sobj) / sizeof(scalar);
|
||||
int64_t Nlow = 1, Nhigh = 1;
|
||||
for (int d = 0; d < dim; d++) Nlow *= grid->_ldimensions[d];
|
||||
for (int d = dim+1; d < Ndim; d++) Nhigh *= grid->_ldimensions[d];
|
||||
int64_t Nperp = Nlow * Nhigh;
|
||||
|
||||
deviceVector<scalar> pgbuf(Nperp * Ncomp * G);
|
||||
scalar *pgbuf_v = &pgbuf[0];
|
||||
int howmany = Ncomp * Nperp;
|
||||
|
||||
scalar div;
|
||||
if (sign == FFTW_BACKWARD) div = 1.0 / G;
|
||||
else if (sign == FFTW_FORWARD) div = 1.0;
|
||||
else GRID_ASSERT(0);
|
||||
|
||||
double t_pencil = 0, t_fft = 0, t_copy = 0, t_shift = 0;
|
||||
double t_total = -usecond();
|
||||
|
||||
result = source;
|
||||
int pc = grid->_processor_coor[dim];
|
||||
|
||||
const Coordinate ldims = grid->_ldimensions;
|
||||
const Coordinate rdims = grid->_rdimensions;
|
||||
const Coordinate sdims = grid->_simd_layout;
|
||||
const Coordinate processors = grid->_processors;
|
||||
|
||||
Coordinate pgdims(Ndim);
|
||||
pgdims[0] = G;
|
||||
for (int d = 0, dd = 1; d < Ndim; d++)
|
||||
if (d != dim) pgdims[dd++] = ldims[d];
|
||||
int64_t pgvol = 1;
|
||||
for (int d = 0; d < Ndim; d++) pgvol *= pgdims[d];
|
||||
|
||||
const int Nsimd = vobj::Nsimd();
|
||||
t_pencil = -usecond();
|
||||
for (int p_idx = 0; p_idx < processors[dim]; p_idx++) {
|
||||
t_copy -= usecond();
|
||||
autoView(r_v, result, AcceleratorRead);
|
||||
accelerator_for(idx, grid->oSites(), vobj::Nsimd(), {
|
||||
#ifdef GRID_SIMT
|
||||
{
|
||||
int lane = acceleratorSIMTlane(Nsimd);
|
||||
#else
|
||||
for (int lane = 0; lane < Nsimd; lane++) {
|
||||
#endif
|
||||
Coordinate icoor, ocoor, pgcoor;
|
||||
Lexicographic::CoorFromIndex(icoor, lane, sdims);
|
||||
Lexicographic::CoorFromIndex(ocoor, idx, rdims);
|
||||
pgcoor[0] = ocoor[dim] + icoor[dim]*rdims[dim] + ((pc+p_idx)%processors[dim])*L;
|
||||
for (int d = 0, dd = 1; d < Ndim; d++)
|
||||
if (d != dim) { pgcoor[dd] = ocoor[d] + icoor[d]*rdims[d]; dd++; }
|
||||
int64_t pgidx;
|
||||
Lexicographic::IndexFromCoor(pgcoor, pgidx, pgdims);
|
||||
vector_type *from = (vector_type *)&r_v[idx];
|
||||
scalar_type stmp;
|
||||
for (int w = 0; w < Ncomp; w++) {
|
||||
stmp = getlane(from[w], lane);
|
||||
pgbuf_v[pgidx + w*pgvol] = stmp;
|
||||
}
|
||||
#ifdef GRID_SIMT
|
||||
}
|
||||
#else
|
||||
}
|
||||
#endif
|
||||
});
|
||||
t_copy += usecond();
|
||||
if (p_idx != processors[dim] - 1) {
|
||||
Lattice<vobj> temp(grid);
|
||||
t_shift -= usecond();
|
||||
temp = Cshift(result, dim, L); result = temp;
|
||||
t_shift += usecond();
|
||||
}
|
||||
}
|
||||
t_pencil += usecond();
|
||||
|
||||
FFTW_scalar *in = (FFTW_scalar *)pgbuf_v;
|
||||
FFTW_scalar *out = (FFTW_scalar *)pgbuf_v;
|
||||
t_fft = -usecond();
|
||||
FFTW<scalar>::fftw_execute_dft(p, in, out, sign);
|
||||
t_fft += usecond();
|
||||
|
||||
flops_call = 5.0 * howmany * G * log2(G);
|
||||
usec = t_fft;
|
||||
flops = flops_call;
|
||||
|
||||
result = Zero();
|
||||
double t_insert = -usecond();
|
||||
{
|
||||
autoView(r_v, result, AcceleratorWrite);
|
||||
accelerator_for(idx, grid->oSites(), Nsimd, {
|
||||
#ifdef GRID_SIMT
|
||||
{
|
||||
int lane = acceleratorSIMTlane(Nsimd);
|
||||
#else
|
||||
for (int lane = 0; lane < Nsimd; lane++) {
|
||||
#endif
|
||||
Coordinate icoor(Ndim), ocoor(Ndim), pgcoor(Ndim);
|
||||
Lexicographic::CoorFromIndex(icoor, lane, sdims);
|
||||
Lexicographic::CoorFromIndex(ocoor, idx, rdims);
|
||||
pgcoor[0] = ocoor[dim] + icoor[dim]*rdims[dim] + pc*L;
|
||||
for (int d = 0, dd = 1; d < Ndim; d++)
|
||||
if (d != dim) { pgcoor[dd] = ocoor[d] + icoor[d]*rdims[d]; dd++; }
|
||||
int64_t pgidx;
|
||||
Lexicographic::IndexFromCoor(pgcoor, pgidx, pgdims);
|
||||
vector_type *to = (vector_type *)&r_v[idx];
|
||||
scalar_type stmp;
|
||||
for (int w = 0; w < Ncomp; w++) {
|
||||
stmp = pgbuf_v[pgidx + w*pgvol];
|
||||
putlane(to[w], stmp, lane);
|
||||
}
|
||||
#ifdef GRID_SIMT
|
||||
}
|
||||
#else
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
result = result * div;
|
||||
t_insert += usecond();
|
||||
t_total += usecond();
|
||||
|
||||
std::cout << GridLogPerformance << " FFT took " << t_total/1.0e6 << " s" << std::endl;
|
||||
std::cout << GridLogPerformance << " FFT pencil " << t_pencil/1.0e6 << " s" << std::endl;
|
||||
std::cout << GridLogPerformance << " of which copy " << t_copy/1.0e6 << " s" << std::endl;
|
||||
std::cout << GridLogPerformance << " of which shift" << t_shift/1.0e6 << " s" << std::endl;
|
||||
std::cout << GridLogPerformance << " FFT kernels " << t_fft/1.0e6 << " s" << std::endl;
|
||||
std::cout << GridLogPerformance << " FFT insert " << t_insert/1.0e6 << " s" << std::endl;
|
||||
}
|
||||
|
||||
class FFT : public FFTbase {
|
||||
class FFT {
|
||||
private:
|
||||
|
||||
double flops;
|
||||
double flops_call;
|
||||
uint64_t usec;
|
||||
|
||||
public:
|
||||
FFT(GridCartesian *grid) : FFTbase(grid) {}
|
||||
~FFT() {}
|
||||
|
||||
static const int forward=FFTW_FORWARD;
|
||||
static const int backward=FFTW_BACKWARD;
|
||||
|
||||
double Flops(void) {return flops;}
|
||||
double MFlops(void) {return flops/usec;}
|
||||
double USec(void) {return (double)usec;}
|
||||
|
||||
FFT ( GridCartesian * grid )
|
||||
{
|
||||
flops=0;
|
||||
usec =0;
|
||||
};
|
||||
|
||||
~FFT ( void) {
|
||||
// delete sgrid;
|
||||
}
|
||||
|
||||
template<class vobj>
|
||||
void FFT_dim_mask(Lattice<vobj> &result, const Lattice<vobj> &source, Coordinate mask, int sign) {
|
||||
const int Ndim = _grid->Nd();
|
||||
void FFT_dim_mask(Lattice<vobj> &result,const Lattice<vobj> &source,Coordinate mask,int sign){
|
||||
|
||||
// vgrid=result.Grid();
|
||||
// conformable(result.Grid(),vgrid);
|
||||
// conformable(source.Grid(),vgrid);
|
||||
const int Ndim = source.Grid()->Nd();
|
||||
Lattice<vobj> tmp = source;
|
||||
for (int d = 0; d < Ndim; d++) {
|
||||
if (mask[d]) {
|
||||
FFT_dim(result, tmp, d, sign);
|
||||
tmp = result;
|
||||
for(int d=0;d<Ndim;d++){
|
||||
if( mask[d] ) {
|
||||
FFT_dim(result,tmp,d,sign);
|
||||
tmp=result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<class vobj>
|
||||
void FFT_all_dim(Lattice<vobj> &result, const Lattice<vobj> &source, int sign) {
|
||||
Coordinate mask(_grid->Nd(), 1);
|
||||
FFT_dim_mask(result, source, mask, sign);
|
||||
void FFT_all_dim(Lattice<vobj> &result,const Lattice<vobj> &source,int sign){
|
||||
const int Ndim = source.Grid()->Nd();
|
||||
Coordinate mask(Ndim,1);
|
||||
FFT_dim_mask(result,source,mask,sign);
|
||||
}
|
||||
|
||||
template<class vobj>
|
||||
void FFT_dim(Lattice<vobj> &result, const Lattice<vobj> &source, int dim, int sign) {
|
||||
GRID_ASSERT(source.Grid() == _grid);
|
||||
GRID_ASSERT(result.Grid() == _grid);
|
||||
conformable(result.Grid(), source.Grid());
|
||||
|
||||
typedef typename vobj::scalar_type scalar;
|
||||
template<class vobj>
|
||||
void FFT_dim(Lattice<vobj> &result,const Lattice<vobj> &source,int dim, int sign){
|
||||
const int Ndim = source.Grid()->Nd();
|
||||
GridBase *grid = source.Grid();
|
||||
conformable(result.Grid(),source.Grid());
|
||||
|
||||
int L = grid->_ldimensions[dim];
|
||||
int G = grid->_fdimensions[dim];
|
||||
|
||||
Coordinate layout(Ndim,1);
|
||||
|
||||
// Construct pencils
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
typedef typename vobj::scalar_type scalar;
|
||||
typedef typename vobj::scalar_type scalar_type;
|
||||
typedef typename vobj::vector_type vector_type;
|
||||
|
||||
//std::cout << "CPU view" << std::endl;
|
||||
|
||||
typedef typename FFTW<scalar>::FFTW_scalar FFTW_scalar;
|
||||
typedef typename FFTW<scalar>::FFTW_plan FFTW_plan;
|
||||
|
||||
int Ncomp = sizeof(sobj)/sizeof(scalar);
|
||||
int64_t Nlow = 1;
|
||||
int64_t Nhigh = 1;
|
||||
|
||||
const int Ndim = _grid->Nd();
|
||||
int G = _grid->_fdimensions[dim];
|
||||
int Ncomp = sizeof(sobj) / sizeof(scalar);
|
||||
int64_t Nperp = 1;
|
||||
for (int d = 0; d < Ndim; d++)
|
||||
if (d != dim) Nperp *= _grid->_ldimensions[d];
|
||||
int n[] = {G};
|
||||
int howmany = Ncomp * Nperp;
|
||||
|
||||
deviceVector<scalar> dummy(2);
|
||||
FFTW_scalar *buf = (FFTW_scalar *)&dummy[0];
|
||||
FFTW_plan p = FFTW<scalar>::fftw_plan_many_dft(1, n, howmany,
|
||||
buf, n, 1, G,
|
||||
buf, n, 1, G,
|
||||
sign, FFTW_ESTIMATE);
|
||||
FFT_dim_execute(result, source, dim, sign, p, _grid, flops, flops_call, usec);
|
||||
FFTW<scalar>::fftw_destroy_plan(p);
|
||||
}
|
||||
};
|
||||
|
||||
template<class vobj>
|
||||
class PlannedFFT : public FFTbase {
|
||||
private:
|
||||
typedef typename vobj::scalar_type scalar;
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
typedef typename vobj::vector_type vector_type;
|
||||
typedef typename FFTW<scalar>::FFTW_scalar FFTW_scalar;
|
||||
typedef typename FFTW<scalar>::FFTW_plan FFTW_plan;
|
||||
|
||||
std::vector<FFTW_plan> forward_plans;
|
||||
std::vector<FFTW_plan> backward_plans;
|
||||
|
||||
void PlanCreate() {
|
||||
const int Ndim = _grid->Nd();
|
||||
forward_plans.resize(Ndim);
|
||||
backward_plans.resize(Ndim);
|
||||
|
||||
for (int d = 0; d < Ndim; d++) {
|
||||
int G = _grid->_fdimensions[d];
|
||||
int Ncomp = sizeof(sobj) / sizeof(scalar);
|
||||
int64_t Nperp = 1;
|
||||
for (int dd = 0; dd < Ndim; dd++)
|
||||
if (dd != d) Nperp *= _grid->_ldimensions[dd];
|
||||
int howmany = Ncomp * (int)Nperp;
|
||||
int n[] = {G};
|
||||
|
||||
deviceVector<scalar> dummy(2);
|
||||
FFTW_scalar *buf = (FFTW_scalar *)&dummy[0];
|
||||
|
||||
forward_plans[d] = FFTW<scalar>::fftw_plan_many_dft(1, n, howmany, buf, n, 1, G, buf, n, 1, G, FFTW_FORWARD, FFTW_ESTIMATE);
|
||||
backward_plans[d] = FFTW<scalar>::fftw_plan_many_dft(1, n, howmany, buf, n, 1, G, buf, n, 1, G, FFTW_BACKWARD, FFTW_ESTIMATE);
|
||||
for(int d=0;d<dim;d++){
|
||||
Nlow*=grid->_ldimensions[d];
|
||||
}
|
||||
}
|
||||
for(int d=dim+1;d<Ndim;d++){
|
||||
Nhigh*=grid->_ldimensions[d];
|
||||
}
|
||||
int64_t Nperp=Nlow*Nhigh;
|
||||
|
||||
deviceVector<scalar> pgbuf; // Layout is [perp][component][dim]
|
||||
pgbuf.resize(Nperp*Ncomp*G);
|
||||
scalar *pgbuf_v = &pgbuf[0];
|
||||
|
||||
int rank = 1; /* 1d transforms */
|
||||
int n[] = {G}; /* 1d transforms of length G */
|
||||
int howmany = Ncomp * Nperp;
|
||||
int odist,idist,istride,ostride;
|
||||
idist = odist = G; /* Distance between consecutive FT's */
|
||||
istride = ostride = 1; /* Distance between two elements in the same FT */
|
||||
int *inembed = n, *onembed = n;
|
||||
|
||||
scalar div;
|
||||
if ( sign == backward ) div = 1.0/G;
|
||||
else if ( sign == forward ) div = 1.0;
|
||||
else GRID_ASSERT(0);
|
||||
|
||||
void PlanDestroy() {
|
||||
for (auto p : forward_plans) FFTW<scalar>::fftw_destroy_plan(p);
|
||||
for (auto p : backward_plans) FFTW<scalar>::fftw_destroy_plan(p);
|
||||
forward_plans.clear();
|
||||
backward_plans.clear();
|
||||
}
|
||||
double t_pencil=0;
|
||||
double t_fft =0;
|
||||
double t_total =-usecond();
|
||||
// std::cout << GridLogPerformance<<"Making FFTW plan" << std::endl;
|
||||
/*
|
||||
*
|
||||
*/
|
||||
FFTW_plan p;
|
||||
{
|
||||
FFTW_scalar *in = (FFTW_scalar *)&pgbuf_v[0];
|
||||
FFTW_scalar *out= (FFTW_scalar *)&pgbuf_v[0];
|
||||
p = FFTW<scalar>::fftw_plan_many_dft(rank,n,howmany,
|
||||
in,inembed,
|
||||
istride,idist,
|
||||
out,onembed,
|
||||
ostride, odist,
|
||||
sign,FFTW_ESTIMATE);
|
||||
}
|
||||
|
||||
// Barrel shift and collect global pencil
|
||||
// std::cout << GridLogPerformance<<"Making pencil" << std::endl;
|
||||
Coordinate lcoor(Ndim), gcoor(Ndim);
|
||||
double t_copy=0;
|
||||
double t_shift=0;
|
||||
t_pencil = -usecond();
|
||||
result = source;
|
||||
int pc = grid->_processor_coor[dim];
|
||||
|
||||
public:
|
||||
PlannedFFT(GridCartesian *grid) : FFTbase(grid) { PlanCreate(); }
|
||||
~PlannedFFT() { PlanDestroy(); }
|
||||
const Coordinate ldims = grid->_ldimensions;
|
||||
const Coordinate rdims = grid->_rdimensions;
|
||||
const Coordinate sdims = grid->_simd_layout;
|
||||
|
||||
void FFT_dim_mask(Lattice<vobj> &result, const Lattice<vobj> &source, Coordinate mask, int sign) {
|
||||
const int Ndim = _grid->Nd();
|
||||
Lattice<vobj> tmp = source;
|
||||
for (int d = 0; d < Ndim; d++) {
|
||||
if (mask[d]) {
|
||||
FFT_dim(result, tmp, d, sign);
|
||||
tmp = result;
|
||||
Coordinate processors = grid->_processors;
|
||||
Coordinate pgdims(Ndim);
|
||||
pgdims[0] = G;
|
||||
for(int d=0, dd=1;d<Ndim;d++){
|
||||
if ( d!=dim ) pgdims[dd++] = ldims[d];
|
||||
}
|
||||
int64_t pgvol=1;
|
||||
for(int d=0;d<Ndim;d++) pgvol*=pgdims[d];
|
||||
|
||||
const int Nsimd = vobj::Nsimd();
|
||||
for(int p=0;p<processors[dim];p++) {
|
||||
t_copy-=usecond();
|
||||
autoView(r_v,result,AcceleratorRead);
|
||||
accelerator_for(idx, grid->oSites(), vobj::Nsimd(), {
|
||||
#ifdef GRID_SIMT
|
||||
{
|
||||
int lane=acceleratorSIMTlane(Nsimd); // buffer lane
|
||||
#else
|
||||
for(int lane=0;lane<Nsimd;lane++) {
|
||||
#endif
|
||||
Coordinate icoor;
|
||||
Coordinate ocoor;
|
||||
Coordinate pgcoor;
|
||||
|
||||
Lexicographic::CoorFromIndex(icoor,lane,sdims);
|
||||
Lexicographic::CoorFromIndex(ocoor,idx,rdims);
|
||||
|
||||
pgcoor[0] = ocoor[dim] + icoor[dim]*rdims[dim] + ((pc+p)%processors[dim])*L;
|
||||
for(int d=0,dd=1;d<Ndim;d++){
|
||||
if ( d!=dim ) {
|
||||
pgcoor[dd] = ocoor[d] + icoor[d]*rdims[d];
|
||||
dd++;
|
||||
}
|
||||
}
|
||||
|
||||
// Map coordinates in lattice layout to FFTW index
|
||||
int64_t pgidx;
|
||||
Lexicographic::IndexFromCoor(pgcoor,pgidx,pgdims);
|
||||
|
||||
vector_type *from = (vector_type *)&r_v[idx];
|
||||
scalar_type stmp;
|
||||
for(int w=0;w<Ncomp;w++){
|
||||
int64_t pg_idx = pgidx + w*pgvol;
|
||||
stmp = getlane(from[w], lane);
|
||||
pgbuf_v[pg_idx] = stmp;
|
||||
}
|
||||
#ifdef GRID_SIMT
|
||||
}
|
||||
#else
|
||||
}
|
||||
#endif
|
||||
});
|
||||
|
||||
t_copy+=usecond();
|
||||
if (p != processors[dim] - 1) {
|
||||
Lattice<vobj> temp(grid);
|
||||
t_shift-=usecond();
|
||||
temp = Cshift(result,dim,L); result = temp;
|
||||
t_shift+=usecond();
|
||||
}
|
||||
}
|
||||
}
|
||||
t_pencil += usecond();
|
||||
|
||||
FFTW_scalar *in = (FFTW_scalar *)pgbuf_v;
|
||||
FFTW_scalar *out= (FFTW_scalar *)pgbuf_v;
|
||||
t_fft = -usecond();
|
||||
FFTW<scalar>::fftw_execute_dft(p,in,out,sign);
|
||||
t_fft += usecond();
|
||||
|
||||
// performance counting
|
||||
flops_call = 5.0*howmany*G*log2(G);
|
||||
usec = t_fft;
|
||||
flops= flops_call;
|
||||
|
||||
void FFT_all_dim(Lattice<vobj> &result, const Lattice<vobj> &source, int sign) {
|
||||
Coordinate mask(_grid->Nd(), 1);
|
||||
FFT_dim_mask(result, source, mask, sign);
|
||||
}
|
||||
result = Zero();
|
||||
|
||||
double t_insert = -usecond();
|
||||
{
|
||||
autoView(r_v,result,AcceleratorWrite);
|
||||
accelerator_for(idx,grid->oSites(),Nsimd,{
|
||||
#ifdef GRID_SIMT
|
||||
{
|
||||
int lane=acceleratorSIMTlane(Nsimd); // buffer lane
|
||||
#else
|
||||
for(int lane=0;lane<Nsimd;lane++) {
|
||||
#endif
|
||||
Coordinate icoor(Ndim);
|
||||
Coordinate ocoor(Ndim);
|
||||
Coordinate pgcoor(Ndim);
|
||||
|
||||
void FFT_dim(Lattice<vobj> &result, const Lattice<vobj> &source, int dim, int sign) {
|
||||
GRID_ASSERT(source.Grid() == _grid);
|
||||
GRID_ASSERT(result.Grid() == _grid);
|
||||
GRID_ASSERT((int)forward_plans.size() == _grid->Nd());
|
||||
conformable(result.Grid(), source.Grid());
|
||||
FFTW_plan p = (sign == forward ? forward_plans : backward_plans)[dim];
|
||||
FFT_dim_execute(result, source, dim, sign, p, _grid, flops, flops_call, usec);
|
||||
Lexicographic::CoorFromIndex(icoor,lane,sdims);
|
||||
Lexicographic::CoorFromIndex(ocoor,idx,rdims);
|
||||
|
||||
pgcoor[0] = ocoor[dim] + icoor[dim]*rdims[dim] + pc*L;
|
||||
for(int d=0,dd=1;d<Ndim;d++){
|
||||
if ( d!=dim ) {
|
||||
pgcoor[dd] = ocoor[d] + icoor[d]*rdims[d];
|
||||
dd++;
|
||||
}
|
||||
}
|
||||
// Map coordinates in lattice layout to FFTW index
|
||||
int64_t pgidx;
|
||||
Lexicographic::IndexFromCoor(pgcoor,pgidx,pgdims);
|
||||
|
||||
vector_type *to = (vector_type *)&r_v[idx];
|
||||
scalar_type stmp;
|
||||
for(int w=0;w<Ncomp;w++){
|
||||
int64_t pg_idx = pgidx + w*pgvol;
|
||||
stmp = pgbuf_v[pg_idx];
|
||||
putlane(to[w], stmp, lane);
|
||||
}
|
||||
|
||||
#ifdef GRID_SIMT
|
||||
}
|
||||
#else
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
result = result*div;
|
||||
|
||||
t_insert +=usecond();
|
||||
|
||||
// destroying plan
|
||||
FFTW<scalar>::fftw_destroy_plan(p);
|
||||
|
||||
t_total +=usecond();
|
||||
|
||||
std::cout <<GridLogPerformance<< " FFT took "<<t_total/1.0e6 <<" s" << std::endl;
|
||||
std::cout <<GridLogPerformance<< " FFT pencil "<<t_pencil/1.0e6 <<" s" << std::endl;
|
||||
std::cout <<GridLogPerformance<< " of which copy "<<t_copy/1.0e6 <<" s" << std::endl;
|
||||
std::cout <<GridLogPerformance<< " of which shift"<<t_shift/1.0e6 <<" s" << std::endl;
|
||||
std::cout <<GridLogPerformance<< " FFT kernels "<<t_fft/1.0e6 <<" s" << std::endl;
|
||||
std::cout <<GridLogPerformance<< " FFT insert "<<t_insert/1.0e6 <<" s" << std::endl;
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -68,59 +68,6 @@ NAMESPACE_BEGIN(Grid);
|
||||
enum GridBLASOperation_t { GridBLAS_OP_N, GridBLAS_OP_T, GridBLAS_OP_C } ;
|
||||
enum GridBLASPrecision_t { GridBLAS_PRECISION_DEFAULT, GridBLAS_PRECISION_16F, GridBLAS_PRECISION_16BF, GridBLAS_PRECISION_TF32 };
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// BLAS scalar constants: the put() wrapper OWNS the residency policy so
|
||||
// call sites just pass values (scalars-live-on-the-host rule).
|
||||
//
|
||||
// Policy per backend:
|
||||
// - CUDA / HIP : handles are put in HOST pointer mode at Init (cuBLAS docs
|
||||
// 2.2.7: host mode is the documented default; 2.1.5: host-mode scalars
|
||||
// are consumed AT CALL TIME, "can be freed just after the return of the
|
||||
// call even though the kernel launch is asynchronous"). put() stores
|
||||
// the value in persistent host memory and returns its address: ZERO
|
||||
// host->device copies.
|
||||
// - SYCL : the oneMKL group-API alpha/beta arrays are dereferenced
|
||||
// USM-side (spec is silent for the group API; implementation observed
|
||||
// to require USM-accessible storage -- host stack pointers fault).
|
||||
// put() keeps a device-resident copy with VALUE CACHING: the copy is
|
||||
// issued only when the value changes (accumulation pattern
|
||||
// beta = (p==0 ? 0 : 1) costs two copies per Mult instead of npoint).
|
||||
//
|
||||
// Motivation (rocprof, Frontier, 2026-08-13): per-call alpha/beta device
|
||||
// staging generated ~92k tiny staged hipMemcpys in a 12s solve window
|
||||
// (~26% of host API time) at the latency-bound coarse level.
|
||||
// NB not thread safe -- matches the single-threaded host BLAS call
|
||||
// pattern of the per-call staging it replaces.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
template<class T>
|
||||
class GridBLASDeviceConstant {
|
||||
#ifdef GRID_SYCL
|
||||
deviceVector<T> dev;
|
||||
T host;
|
||||
int valid;
|
||||
public:
|
||||
GridBLASDeviceConstant() : dev(1), valid(0) {};
|
||||
T * put(T v) {
|
||||
if ( (!valid) || (v != host) ) {
|
||||
acceleratorCopyToDevice((void *)&v,(void *)&dev[0],sizeof(T));
|
||||
host = v;
|
||||
valid = 1;
|
||||
}
|
||||
return &dev[0];
|
||||
}
|
||||
#else
|
||||
// CUDA / HIP in HOST pointer mode (and CPU/Eigen, where the pointer is
|
||||
// unused): persistent host storage, no copies ever.
|
||||
T host;
|
||||
public:
|
||||
GridBLASDeviceConstant() {};
|
||||
T * put(T v) {
|
||||
host = v;
|
||||
return &host;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
class GridBLAS {
|
||||
public:
|
||||
|
||||
@@ -134,31 +81,11 @@ public:
|
||||
#ifdef GRID_CUDA
|
||||
std::cout << "cublasCreate"<<std::endl;
|
||||
cublasCreate(&gridblasHandle);
|
||||
// HOST pointer mode: scalars consumed at call time from host memory
|
||||
// (cuBLAS docs 2.1.5/2.2.7) -- no device staging of alpha/beta.
|
||||
// DEVICE mode would be a deliberate opt-in for device-produced
|
||||
// scalars (e.g. a future graph-captured solver).
|
||||
cublasSetPointerMode(gridblasHandle, CUBLAS_POINTER_MODE_HOST);
|
||||
{
|
||||
cublasPointerMode_t pm;
|
||||
cublasGetPointerMode(gridblasHandle,&pm);
|
||||
std::cout << "GridBLAS: cuBLAS pointer mode "
|
||||
<< ((pm==CUBLAS_POINTER_MODE_DEVICE)?"DEVICE":"HOST") <<std::endl;
|
||||
}
|
||||
cublasSetPointerMode(gridblasHandle, CUBLAS_POINTER_MODE_DEVICE);
|
||||
#endif
|
||||
#ifdef GRID_HIP
|
||||
std::cout << "hipblasCreate"<<std::endl;
|
||||
hipblasCreate(&gridblasHandle);
|
||||
// Explicit HOST mode: the hipBLAS default is UNDOCUMENTED in the
|
||||
// headers (enum 0 == HOST by cuBLAS-mirroring convention only);
|
||||
// set it and print it so every log carries the ground truth.
|
||||
hipblasSetPointerMode(gridblasHandle, HIPBLAS_POINTER_MODE_HOST);
|
||||
{
|
||||
hipblasPointerMode_t pm;
|
||||
hipblasGetPointerMode(gridblasHandle,&pm);
|
||||
std::cout << "GridBLAS: hipBLAS pointer mode "
|
||||
<< ((pm==HIPBLAS_POINTER_MODE_DEVICE)?"DEVICE":"HOST") <<std::endl;
|
||||
}
|
||||
#endif
|
||||
#ifdef GRID_SYCL
|
||||
gridblasHandle = theGridAccelerator;
|
||||
@@ -313,11 +240,11 @@ public:
|
||||
if(OpB!=GridBLAS_OP_N)
|
||||
ldb = n;
|
||||
|
||||
// Cached device constants: copy only on value change (see GridBLASDeviceConstant)
|
||||
static GridBLASDeviceConstant<ComplexD> alpha_c;
|
||||
static GridBLASDeviceConstant<ComplexD> beta_c;
|
||||
ComplexD *alpha_p = alpha_c.put(alpha);
|
||||
ComplexD *beta_p = beta_c.put(beta);
|
||||
static deviceVector<ComplexD> alpha_p(1);
|
||||
static deviceVector<ComplexD> beta_p(1);
|
||||
// can prestore the 1 and the zero on device
|
||||
acceleratorCopyToDevice((void *)&alpha,(void *)&alpha_p[0],sizeof(ComplexD));
|
||||
acceleratorCopyToDevice((void *)&beta ,(void *)&beta_p[0],sizeof(ComplexD));
|
||||
RealD t0=usecond();
|
||||
// std::cout << "ZgemmBatched mnk "<<m<<","<<n<<","<<k<<" count "<<batchCount<<std::endl;
|
||||
#ifdef GRID_HIP
|
||||
@@ -352,7 +279,7 @@ public:
|
||||
(hipblasDoubleComplex **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
#endif
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
// std::cout << " hipblas return code " <<(int)err<<std::endl;
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
@@ -571,11 +498,11 @@ public:
|
||||
lda = k;
|
||||
if(OpB!=GridBLAS_OP_N)
|
||||
ldb = n;
|
||||
// Cached device constants: copy only on value change (see GridBLASDeviceConstant)
|
||||
static GridBLASDeviceConstant<ComplexF> alpha_c;
|
||||
static GridBLASDeviceConstant<ComplexF> beta_c;
|
||||
ComplexF *alpha_p = alpha_c.put(alpha);
|
||||
ComplexF *beta_p = beta_c.put(beta);
|
||||
static deviceVector<ComplexF> alpha_p(1);
|
||||
static deviceVector<ComplexF> beta_p(1);
|
||||
// can prestore the 1 and the zero on device
|
||||
acceleratorCopyToDevice((void *)&alpha,(void *)&alpha_p[0],sizeof(ComplexF));
|
||||
acceleratorCopyToDevice((void *)&beta ,(void *)&beta_p[0],sizeof(ComplexF));
|
||||
RealD t0=usecond();
|
||||
|
||||
GRID_ASSERT(Bkn.size()==batchCount);
|
||||
@@ -614,7 +541,6 @@ public:
|
||||
batchCount);
|
||||
|
||||
#endif
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
@@ -651,7 +577,6 @@ public:
|
||||
(void **)&Cmn[0], CUDA_C_32F, ldc,
|
||||
batchCount, compute_precision, CUBLAS_GEMM_DEFAULT);
|
||||
}
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
GRID_ASSERT(err==CUBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_SYCL
|
||||
@@ -768,456 +693,6 @@ public:
|
||||
RealD bytes = 1.0*sizeof(ComplexF)*(m*k+k*n+m*n)*batchCount;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Explicit-leading-dimension complex single GEMM.
|
||||
//
|
||||
// A,B,C may be SLICES of larger parent allocations: lda/ldb/ldc are the
|
||||
// PARENT strides (>= the compact values the ten-argument overload derives).
|
||||
// Motivating use: software split-K for tiny-output/huge-K dense multiplies
|
||||
// (arXiv:2409.03904 fig 11; cf MultiRHSBlockCGLinalg) -- batch over K-chunks
|
||||
// of a dense slab by pointer offset j*Kchunk with lda = the full K extent,
|
||||
// then reduce the partial C's. Backends pass lda straight through; only
|
||||
// the compact overload invented them.
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
void gemmBatched(GridBLASOperation_t OpA,
|
||||
GridBLASOperation_t OpB,
|
||||
int m,int n, int k,
|
||||
ComplexF alpha,
|
||||
deviceVector<ComplexF*> &Amk, int lda,
|
||||
deviceVector<ComplexF*> &Bkn, int ldb,
|
||||
ComplexF beta,
|
||||
deviceVector<ComplexF*> &Cmn, int ldc,
|
||||
GridBLASPrecision_t precision = GridBLAS_PRECISION_DEFAULT)
|
||||
{
|
||||
RealD t2=usecond();
|
||||
int32_t batchCount = Amk.size();
|
||||
|
||||
GRID_ASSERT( lda >= ((OpA==GridBLAS_OP_N) ? m : k) );
|
||||
GRID_ASSERT( ldb >= ((OpB==GridBLAS_OP_N) ? k : n) );
|
||||
GRID_ASSERT( ldc >= m );
|
||||
|
||||
// Cached device constants: copy only on value change (see GridBLASDeviceConstant)
|
||||
static GridBLASDeviceConstant<ComplexF> alpha_c;
|
||||
static GridBLASDeviceConstant<ComplexF> beta_c;
|
||||
ComplexF *alpha_p = alpha_c.put(alpha);
|
||||
ComplexF *beta_p = beta_c.put(beta);
|
||||
RealD t0=usecond();
|
||||
|
||||
GRID_ASSERT(Bkn.size()==batchCount);
|
||||
GRID_ASSERT(Cmn.size()==batchCount);
|
||||
#ifdef GRID_HIP
|
||||
GRID_ASSERT(precision == GridBLAS_PRECISION_DEFAULT);
|
||||
hipblasOperation_t hOpA;
|
||||
hipblasOperation_t hOpB;
|
||||
if ( OpA == GridBLAS_OP_N ) hOpA = HIPBLAS_OP_N;
|
||||
if ( OpA == GridBLAS_OP_T ) hOpA = HIPBLAS_OP_T;
|
||||
if ( OpA == GridBLAS_OP_C ) hOpA = HIPBLAS_OP_C;
|
||||
if ( OpB == GridBLAS_OP_N ) hOpB = HIPBLAS_OP_N;
|
||||
if ( OpB == GridBLAS_OP_T ) hOpB = HIPBLAS_OP_T;
|
||||
if ( OpB == GridBLAS_OP_C ) hOpB = HIPBLAS_OP_C;
|
||||
#if defined(HIP_VERSION_MAJOR) && (HIP_VERSION_MAJOR >=7)
|
||||
auto err = hipblasCgemmBatched(gridblasHandle,
|
||||
hOpA,
|
||||
hOpB,
|
||||
m,n,k,
|
||||
(hipComplex *) &alpha_p[0],
|
||||
(hipComplex **)&Amk[0], lda,
|
||||
(hipComplex **)&Bkn[0], ldb,
|
||||
(hipComplex *) &beta_p[0],
|
||||
(hipComplex **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
#else
|
||||
auto err = hipblasCgemmBatched(gridblasHandle,
|
||||
hOpA,
|
||||
hOpB,
|
||||
m,n,k,
|
||||
(hipblasComplex *) &alpha_p[0],
|
||||
(hipblasComplex **)&Amk[0], lda,
|
||||
(hipblasComplex **)&Bkn[0], ldb,
|
||||
(hipblasComplex *) &beta_p[0],
|
||||
(hipblasComplex **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
#endif
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
cublasOperation_t hOpA;
|
||||
cublasOperation_t hOpB;
|
||||
if ( OpA == GridBLAS_OP_N ) hOpA = CUBLAS_OP_N;
|
||||
if ( OpA == GridBLAS_OP_T ) hOpA = CUBLAS_OP_T;
|
||||
if ( OpA == GridBLAS_OP_C ) hOpA = CUBLAS_OP_C;
|
||||
if ( OpB == GridBLAS_OP_N ) hOpB = CUBLAS_OP_N;
|
||||
if ( OpB == GridBLAS_OP_T ) hOpB = CUBLAS_OP_T;
|
||||
if ( OpB == GridBLAS_OP_C ) hOpB = CUBLAS_OP_C;
|
||||
cublasStatus_t err;
|
||||
if (precision == GridBLAS_PRECISION_DEFAULT) {
|
||||
err = cublasCgemmBatched(gridblasHandle,
|
||||
hOpA,
|
||||
hOpB,
|
||||
m,n,k,
|
||||
(cuComplex *) &alpha_p[0],
|
||||
(cuComplex **)&Amk[0], lda,
|
||||
(cuComplex **)&Bkn[0], ldb,
|
||||
(cuComplex *) &beta_p[0],
|
||||
(cuComplex **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
} else {
|
||||
cublasComputeType_t compute_precision = toDataType(precision);
|
||||
err = cublasGemmBatchedEx(gridblasHandle,
|
||||
hOpA,
|
||||
hOpB,
|
||||
m,n,k,
|
||||
(void *) &alpha_p[0],
|
||||
(void **)&Amk[0], CUDA_C_32F, lda,
|
||||
(void **)&Bkn[0], CUDA_C_32F, ldb,
|
||||
(void *) &beta_p[0],
|
||||
(void **)&Cmn[0], CUDA_C_32F, ldc,
|
||||
batchCount, compute_precision, CUBLAS_GEMM_DEFAULT);
|
||||
}
|
||||
GRID_ASSERT(err==CUBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_SYCL
|
||||
GRID_ASSERT(precision == GridBLAS_PRECISION_DEFAULT);
|
||||
int64_t m64=m;
|
||||
int64_t n64=n;
|
||||
int64_t k64=k;
|
||||
int64_t lda64=lda;
|
||||
int64_t ldb64=ldb;
|
||||
int64_t ldc64=ldc;
|
||||
int64_t batchCount64=batchCount;
|
||||
|
||||
oneapi::mkl::transpose iOpA;
|
||||
oneapi::mkl::transpose iOpB;
|
||||
|
||||
if ( OpA == GridBLAS_OP_N ) iOpA = oneapi::mkl::transpose::N;
|
||||
if ( OpA == GridBLAS_OP_T ) iOpA = oneapi::mkl::transpose::T;
|
||||
if ( OpA == GridBLAS_OP_C ) iOpA = oneapi::mkl::transpose::C;
|
||||
if ( OpB == GridBLAS_OP_N ) iOpB = oneapi::mkl::transpose::N;
|
||||
if ( OpB == GridBLAS_OP_T ) iOpB = oneapi::mkl::transpose::T;
|
||||
if ( OpB == GridBLAS_OP_C ) iOpB = oneapi::mkl::transpose::C;
|
||||
|
||||
oneapi::mkl::blas::column_major::gemm_batch(*gridblasHandle,
|
||||
&iOpA,
|
||||
&iOpB,
|
||||
&m64,&n64,&k64,
|
||||
(ComplexF *) &alpha_p[0],
|
||||
(const ComplexF **)&Amk[0], (const int64_t *)&lda64,
|
||||
(const ComplexF **)&Bkn[0], (const int64_t *)&ldb64,
|
||||
(ComplexF *) &beta_p[0],
|
||||
(ComplexF **)&Cmn[0], (const int64_t *)&ldc64,
|
||||
(int64_t)1,&batchCount64,std::vector<sycl::event>());
|
||||
synchronise();
|
||||
#endif
|
||||
#if !defined(GRID_SYCL) && !defined(GRID_CUDA) && !defined(GRID_HIP)
|
||||
GRID_ASSERT(precision == GridBLAS_PRECISION_DEFAULT);
|
||||
// Reference implementation: Eigen with explicit outer stride
|
||||
typedef Eigen::Map<Eigen::MatrixXcf,0,Eigen::OuterStride<> > eMat;
|
||||
if ( (OpA == GridBLAS_OP_N ) && (OpB == GridBLAS_OP_N) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],m,k,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],k,n,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
eCmn = beta * eCmn + alpha * eAmk * eBkn ;
|
||||
else
|
||||
eCmn = alpha * eAmk * eBkn ;
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_C ) && (OpB == GridBLAS_OP_N) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],k,m,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],k,n,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
eCmn = beta * eCmn + alpha * eAmk.adjoint() * eBkn ;
|
||||
else
|
||||
eCmn = alpha * eAmk.adjoint() * eBkn ;
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_T ) && (OpB == GridBLAS_OP_N) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],k,m,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],k,n,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
eCmn = beta * eCmn + alpha * eAmk.transpose() * eBkn ;
|
||||
else
|
||||
eCmn = alpha * eAmk.transpose() * eBkn ;
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_N ) && (OpB == GridBLAS_OP_C) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],m,k,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],n,k,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
eCmn = beta * eCmn + alpha * eAmk * eBkn.adjoint() ;
|
||||
else
|
||||
eCmn = alpha * eAmk * eBkn.adjoint() ;
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_N ) && (OpB == GridBLAS_OP_T) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],m,k,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],n,k,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
eCmn = beta * eCmn + alpha * eAmk * eBkn.transpose() ;
|
||||
else
|
||||
eCmn = alpha * eAmk * eBkn.transpose() ;
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_C ) && (OpB == GridBLAS_OP_C) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],k,m,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],n,k,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
eCmn = beta * eCmn + alpha * eAmk.adjoint() * eBkn.adjoint() ;
|
||||
else
|
||||
eCmn = alpha * eAmk.adjoint() * eBkn.adjoint() ;
|
||||
} );
|
||||
} else if ( (OpA == GridBLAS_OP_T ) && (OpB == GridBLAS_OP_T) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],k,m,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],n,k,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
eCmn = beta * eCmn + alpha * eAmk.transpose() * eBkn.transpose() ;
|
||||
else
|
||||
eCmn = alpha * eAmk.transpose() * eBkn.transpose() ;
|
||||
} );
|
||||
} else {
|
||||
assert(0);
|
||||
}
|
||||
#endif
|
||||
RealD t1=usecond();
|
||||
RealD flops = 8.0*m*n*k*batchCount;
|
||||
RealD bytes = 1.0*sizeof(ComplexF)*(m*k+k*n+m*n)*batchCount;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Explicit-leading-dimension complex double GEMM. Mirror of the ComplexF
|
||||
// overload above; motivating use is the fp64 distributed recursive Schur
|
||||
// inversion (RecursiveSchurInverse), whose operands are column windows of
|
||||
// larger row-slab allocations.
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
void gemmBatched(GridBLASOperation_t OpA,
|
||||
GridBLASOperation_t OpB,
|
||||
int m,int n, int k,
|
||||
ComplexD alpha,
|
||||
deviceVector<ComplexD*> &Amk, int lda,
|
||||
deviceVector<ComplexD*> &Bkn, int ldb,
|
||||
ComplexD beta,
|
||||
deviceVector<ComplexD*> &Cmn, int ldc)
|
||||
{
|
||||
RealD t2=usecond();
|
||||
int32_t batchCount = Amk.size();
|
||||
|
||||
GRID_ASSERT( lda >= ((OpA==GridBLAS_OP_N) ? m : k) );
|
||||
GRID_ASSERT( ldb >= ((OpB==GridBLAS_OP_N) ? k : n) );
|
||||
GRID_ASSERT( ldc >= m );
|
||||
|
||||
// Cached device constants: copy only on value change (see GridBLASDeviceConstant)
|
||||
static GridBLASDeviceConstant<ComplexD> alpha_c;
|
||||
static GridBLASDeviceConstant<ComplexD> beta_c;
|
||||
ComplexD *alpha_p = alpha_c.put(alpha);
|
||||
ComplexD *beta_p = beta_c.put(beta);
|
||||
RealD t0=usecond();
|
||||
|
||||
GRID_ASSERT(Bkn.size()==batchCount);
|
||||
GRID_ASSERT(Cmn.size()==batchCount);
|
||||
#ifdef GRID_HIP
|
||||
hipblasOperation_t hOpA;
|
||||
hipblasOperation_t hOpB;
|
||||
if ( OpA == GridBLAS_OP_N ) hOpA = HIPBLAS_OP_N;
|
||||
if ( OpA == GridBLAS_OP_T ) hOpA = HIPBLAS_OP_T;
|
||||
if ( OpA == GridBLAS_OP_C ) hOpA = HIPBLAS_OP_C;
|
||||
if ( OpB == GridBLAS_OP_N ) hOpB = HIPBLAS_OP_N;
|
||||
if ( OpB == GridBLAS_OP_T ) hOpB = HIPBLAS_OP_T;
|
||||
if ( OpB == GridBLAS_OP_C ) hOpB = HIPBLAS_OP_C;
|
||||
#if defined(HIP_VERSION_MAJOR) && (HIP_VERSION_MAJOR >=7)
|
||||
auto err = hipblasZgemmBatched(gridblasHandle,
|
||||
hOpA,
|
||||
hOpB,
|
||||
m,n,k,
|
||||
(hipDoubleComplex *) &alpha_p[0],
|
||||
(hipDoubleComplex **)&Amk[0], lda,
|
||||
(hipDoubleComplex **)&Bkn[0], ldb,
|
||||
(hipDoubleComplex *) &beta_p[0],
|
||||
(hipDoubleComplex **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
#else
|
||||
auto err = hipblasZgemmBatched(gridblasHandle,
|
||||
hOpA,
|
||||
hOpB,
|
||||
m,n,k,
|
||||
(hipblasDoubleComplex *) &alpha_p[0],
|
||||
(hipblasDoubleComplex **)&Amk[0], lda,
|
||||
(hipblasDoubleComplex **)&Bkn[0], ldb,
|
||||
(hipblasDoubleComplex *) &beta_p[0],
|
||||
(hipblasDoubleComplex **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
#endif
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
cublasOperation_t hOpA;
|
||||
cublasOperation_t hOpB;
|
||||
if ( OpA == GridBLAS_OP_N ) hOpA = CUBLAS_OP_N;
|
||||
if ( OpA == GridBLAS_OP_T ) hOpA = CUBLAS_OP_T;
|
||||
if ( OpA == GridBLAS_OP_C ) hOpA = CUBLAS_OP_C;
|
||||
if ( OpB == GridBLAS_OP_N ) hOpB = CUBLAS_OP_N;
|
||||
if ( OpB == GridBLAS_OP_T ) hOpB = CUBLAS_OP_T;
|
||||
if ( OpB == GridBLAS_OP_C ) hOpB = CUBLAS_OP_C;
|
||||
auto err = cublasZgemmBatched(gridblasHandle,
|
||||
hOpA,
|
||||
hOpB,
|
||||
m,n,k,
|
||||
(cuDoubleComplex *) &alpha_p[0],
|
||||
(cuDoubleComplex **)&Amk[0], lda,
|
||||
(cuDoubleComplex **)&Bkn[0], ldb,
|
||||
(cuDoubleComplex *) &beta_p[0],
|
||||
(cuDoubleComplex **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
GRID_ASSERT(err==CUBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_SYCL
|
||||
int64_t m64=m;
|
||||
int64_t n64=n;
|
||||
int64_t k64=k;
|
||||
int64_t lda64=lda;
|
||||
int64_t ldb64=ldb;
|
||||
int64_t ldc64=ldc;
|
||||
int64_t batchCount64=batchCount;
|
||||
|
||||
oneapi::mkl::transpose iOpA;
|
||||
oneapi::mkl::transpose iOpB;
|
||||
|
||||
if ( OpA == GridBLAS_OP_N ) iOpA = oneapi::mkl::transpose::N;
|
||||
if ( OpA == GridBLAS_OP_T ) iOpA = oneapi::mkl::transpose::T;
|
||||
if ( OpA == GridBLAS_OP_C ) iOpA = oneapi::mkl::transpose::C;
|
||||
if ( OpB == GridBLAS_OP_N ) iOpB = oneapi::mkl::transpose::N;
|
||||
if ( OpB == GridBLAS_OP_T ) iOpB = oneapi::mkl::transpose::T;
|
||||
if ( OpB == GridBLAS_OP_C ) iOpB = oneapi::mkl::transpose::C;
|
||||
|
||||
oneapi::mkl::blas::column_major::gemm_batch(*gridblasHandle,
|
||||
&iOpA,
|
||||
&iOpB,
|
||||
&m64,&n64,&k64,
|
||||
(ComplexD *) &alpha_p[0],
|
||||
(const ComplexD **)&Amk[0], (const int64_t *)&lda64,
|
||||
(const ComplexD **)&Bkn[0], (const int64_t *)&ldb64,
|
||||
(ComplexD *) &beta_p[0],
|
||||
(ComplexD **)&Cmn[0], (const int64_t *)&ldc64,
|
||||
(int64_t)1,&batchCount64,std::vector<sycl::event>());
|
||||
synchronise();
|
||||
#endif
|
||||
#if !defined(GRID_SYCL) && !defined(GRID_CUDA) && !defined(GRID_HIP)
|
||||
// Reference implementation: Eigen with explicit outer stride
|
||||
typedef Eigen::Map<Eigen::MatrixXcd,0,Eigen::OuterStride<> > eMat;
|
||||
if ( (OpA == GridBLAS_OP_N ) && (OpB == GridBLAS_OP_N) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],m,k,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],k,n,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
{
|
||||
eCmn = beta * eCmn + alpha * eAmk * eBkn;
|
||||
}
|
||||
else
|
||||
{
|
||||
eCmn = alpha * eAmk * eBkn;
|
||||
}
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_C ) && (OpB == GridBLAS_OP_N) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],k,m,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],k,n,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
{
|
||||
eCmn = beta * eCmn + alpha * eAmk.adjoint() * eBkn;
|
||||
}
|
||||
else
|
||||
{
|
||||
eCmn = alpha * eAmk.adjoint() * eBkn;
|
||||
}
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_T ) && (OpB == GridBLAS_OP_N) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],k,m,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],k,n,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
{
|
||||
eCmn = beta * eCmn + alpha * eAmk.transpose() * eBkn;
|
||||
}
|
||||
else
|
||||
{
|
||||
eCmn = alpha * eAmk.transpose() * eBkn;
|
||||
}
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_N ) && (OpB == GridBLAS_OP_C) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],m,k,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],n,k,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
{
|
||||
eCmn = beta * eCmn + alpha * eAmk * eBkn.adjoint();
|
||||
}
|
||||
else
|
||||
{
|
||||
eCmn = alpha * eAmk * eBkn.adjoint();
|
||||
}
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_N ) && (OpB == GridBLAS_OP_T) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],m,k,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],n,k,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
{
|
||||
eCmn = beta * eCmn + alpha * eAmk * eBkn.transpose();
|
||||
}
|
||||
else
|
||||
{
|
||||
eCmn = alpha * eAmk * eBkn.transpose();
|
||||
}
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_C ) && (OpB == GridBLAS_OP_C) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],k,m,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],n,k,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
{
|
||||
eCmn = beta * eCmn + alpha * eAmk.adjoint() * eBkn.adjoint();
|
||||
}
|
||||
else
|
||||
{
|
||||
eCmn = alpha * eAmk.adjoint() * eBkn.adjoint();
|
||||
}
|
||||
});
|
||||
} else if ( (OpA == GridBLAS_OP_T ) && (OpB == GridBLAS_OP_T) ) {
|
||||
thread_for (p, batchCount, {
|
||||
eMat eAmk(Amk[p],k,m,Eigen::OuterStride<>(lda));
|
||||
eMat eBkn(Bkn[p],n,k,Eigen::OuterStride<>(ldb));
|
||||
eMat eCmn(Cmn[p],m,n,Eigen::OuterStride<>(ldc));
|
||||
if (std::abs(beta) != 0.0)
|
||||
{
|
||||
eCmn = beta * eCmn + alpha * eAmk.transpose() * eBkn.transpose();
|
||||
}
|
||||
else
|
||||
{
|
||||
eCmn = alpha * eAmk.transpose() * eBkn.transpose();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
assert(0);
|
||||
}
|
||||
#endif
|
||||
RealD t1=usecond();
|
||||
RealD flops = 8.0*m*n*k*batchCount;
|
||||
RealD bytes = 1.0*sizeof(ComplexD)*(m*k+k*n+m*n)*batchCount;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Single precision real GEMM
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
@@ -1244,11 +719,11 @@ public:
|
||||
lda = k;
|
||||
if(OpB!=GridBLAS_OP_N)
|
||||
ldb = n;
|
||||
// Cached device constants: copy only on value change (see GridBLASDeviceConstant)
|
||||
static GridBLASDeviceConstant<RealF> alpha_c;
|
||||
static GridBLASDeviceConstant<RealF> beta_c;
|
||||
RealF *alpha_p = alpha_c.put(alpha);
|
||||
RealF *beta_p = beta_c.put(beta);
|
||||
static deviceVector<RealF> alpha_p(1);
|
||||
static deviceVector<RealF> beta_p(1);
|
||||
// can prestore the 1 and the zero on device
|
||||
acceleratorCopyToDevice((void *)&alpha,(void *)&alpha_p[0],sizeof(RealF));
|
||||
acceleratorCopyToDevice((void *)&beta ,(void *)&beta_p[0],sizeof(RealF));
|
||||
RealD t0=usecond();
|
||||
|
||||
GRID_ASSERT(Bkn.size()==batchCount);
|
||||
@@ -1272,7 +747,6 @@ public:
|
||||
(float *) &beta_p[0],
|
||||
(float **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
@@ -1405,11 +879,11 @@ public:
|
||||
if(OpB!=GridBLAS_OP_N)
|
||||
ldb = n;
|
||||
|
||||
// Cached device constants: copy only on value change (see GridBLASDeviceConstant)
|
||||
static GridBLASDeviceConstant<RealD> alpha_c;
|
||||
static GridBLASDeviceConstant<RealD> beta_c;
|
||||
RealD *alpha_p = alpha_c.put(alpha);
|
||||
RealD *beta_p = beta_c.put(beta);
|
||||
static deviceVector<RealD> alpha_p(1);
|
||||
static deviceVector<RealD> beta_p(1);
|
||||
// can prestore the 1 and the zero on device
|
||||
acceleratorCopyToDevice((void *)&alpha,(void *)&alpha_p[0],sizeof(RealD));
|
||||
acceleratorCopyToDevice((void *)&beta ,(void *)&beta_p[0],sizeof(RealD));
|
||||
RealD t0=usecond();
|
||||
|
||||
GRID_ASSERT(Bkn.size()==batchCount);
|
||||
@@ -1433,7 +907,6 @@ public:
|
||||
(double *) &beta_p[0],
|
||||
(double **)&Cmn[0], ldc,
|
||||
batchCount);
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
@@ -1661,7 +1134,6 @@ public:
|
||||
(int*) &info[0],
|
||||
(int)batchCount);
|
||||
#endif
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
@@ -1701,7 +1173,6 @@ public:
|
||||
(int)batchCount);
|
||||
#endif
|
||||
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
@@ -1790,7 +1261,6 @@ public:
|
||||
(int)batchCount);
|
||||
|
||||
#endif
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
@@ -1834,7 +1304,6 @@ public:
|
||||
(int*) &info[0],
|
||||
(int)batchCount);
|
||||
#endif
|
||||
// std::cout << " hipblas return code " <<(int)err<<" "<<__LINE__<<std::endl;
|
||||
GRID_ASSERT(err==HIPBLAS_STATUS_SUCCESS);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: BatchedInverse.h
|
||||
|
||||
Copyright (C) 2026
|
||||
|
||||
Author: Peter Boyle <pboyle@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#pragma once
|
||||
|
||||
#include <Grid/algorithms/blas/BatchedBlas.h>
|
||||
|
||||
#ifdef GRID_HIP
|
||||
#include <rocsolver/rocsolver.h>
|
||||
#endif
|
||||
// GRID_CUDA: batched LU inversion lives in cuBLAS (getrfBatched/getriBatched);
|
||||
// cublas_v2.h already included via BatchedBlas.h.
|
||||
// GRID_SYCL: oneapi/mkl.hpp already included via BatchedBlas.h (lapack::getrf/getri).
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// GridBLASInverse: cross-platform batched dense matrix inversion.
|
||||
//
|
||||
// HIGH LEVEL contract (deliberately NOT a getrf/getrs interface): invert a
|
||||
// batch of dense N x N matrices IN PLACE,
|
||||
//
|
||||
// A[i] <- A[i]^{-1} i = 0 .. batchCount-1
|
||||
//
|
||||
// Layout: column major, lda = N, contiguous per batch element; pointer list
|
||||
// exactly as GridBLAS::gemmBatched (deviceVector<T*> of device pointers).
|
||||
// Each backend chooses HOW:
|
||||
// HIP : rocSOLVER getrf_batched + getri_batched
|
||||
// CUDA : cuBLAS getrfBatched + getriBatched (out-of-place getri; workspace
|
||||
// hidden here, result copied back so the surface stays in-place)
|
||||
// SYCL : oneMKL LAPACK getrf + getri per batch element (USM, in-order queue)
|
||||
// CPU : Eigen PartialPivLU (the correctness oracle for all of the above)
|
||||
//
|
||||
// The int32 vendor-batched entry points bound N < 2^31 (asserted); the huge
|
||||
// single-matrix ILP64 path (getrf_64 + blocked identity-getrs harvest, proven
|
||||
// in the dense coarse-coarse setup at N=69120) migrates here as a batch==1
|
||||
// large-N dispatch in a follow-up -- the recursive Schur leaves are the
|
||||
// batched consumers this surface is shaped for.
|
||||
//
|
||||
// NB GPU-backend call signatures are written to vendor documentation but the
|
||||
// air-gapped development loop compiles only the CPU/Eigen path; verify the
|
||||
// rocSOLVER/cuBLAS/oneMKL calls against headers on first device compile.
|
||||
// Semantics are locked by the CPU unit test (Test_batched_blas).
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
class GridBLASInverse {
|
||||
public:
|
||||
|
||||
#ifdef GRID_HIP
|
||||
// rocSOLVER runs on a rocblas_handle (distinct type from hipblasHandle_t)
|
||||
static rocblas_handle & Handle(void) {
|
||||
static rocblas_handle h;
|
||||
static int init = 0;
|
||||
if ( !init ) {
|
||||
auto st = rocblas_create_handle(&h);
|
||||
GRID_ASSERT(st == rocblas_status_success);
|
||||
init = 1;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
// cuBLAS batched LU shares the GridBLAS handle
|
||||
static cublasHandle_t & Handle(void) {
|
||||
GridBLAS::Init();
|
||||
return GridBLAS::gridblasHandle;
|
||||
}
|
||||
#endif
|
||||
#ifdef GRID_SYCL
|
||||
static sycl::queue * & Handle(void) {
|
||||
GridBLAS::Init();
|
||||
return GridBLAS::gridblasHandle;
|
||||
}
|
||||
#endif
|
||||
|
||||
GridBLASInverse() {};
|
||||
~GridBLASInverse() {};
|
||||
|
||||
void inverseBatched(int64_t N, deviceVector<ComplexF*> &Amat)
|
||||
{
|
||||
int32_t batchCount = Amat.size();
|
||||
GRID_ASSERT(batchCount > 0);
|
||||
|
||||
#ifdef GRID_HIP
|
||||
GRID_ASSERT( N < 2147483647L );
|
||||
rocblas_int n = (rocblas_int)N;
|
||||
rocblas_int lda = (rocblas_int)N;
|
||||
|
||||
deviceVector<rocblas_int> ipiv((uint64_t)batchCount*N);
|
||||
deviceVector<rocblas_int> info(batchCount);
|
||||
|
||||
auto st1 = rocsolver_cgetrf_batched(Handle(), n, n,
|
||||
(rocblas_float_complex *const *)&Amat[0], lda,
|
||||
&ipiv[0], (rocblas_stride)N,
|
||||
&info[0], batchCount);
|
||||
GRID_ASSERT(st1 == rocblas_status_success);
|
||||
auto st2 = rocsolver_cgetri_batched(Handle(), n,
|
||||
(rocblas_float_complex *const *)&Amat[0], lda,
|
||||
&ipiv[0], (rocblas_stride)N,
|
||||
&info[0], batchCount);
|
||||
GRID_ASSERT(st2 == rocblas_status_success);
|
||||
accelerator_barrier();
|
||||
std::vector<rocblas_int> info_h(batchCount);
|
||||
acceleratorCopyFromDevice(&info[0],&info_h[0],batchCount*sizeof(rocblas_int));
|
||||
for(int i=0;i<batchCount;i++) GRID_ASSERT(info_h[i]==0); // singular pivot => abort loudly
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
GRID_ASSERT( N < 2147483647L );
|
||||
int n = (int)N;
|
||||
|
||||
deviceVector<int> ipiv((uint64_t)batchCount*N);
|
||||
deviceVector<int> info(batchCount);
|
||||
|
||||
auto st1 = cublasCgetrfBatched(Handle(), n,
|
||||
(cuComplex **)&Amat[0], n,
|
||||
&ipiv[0], &info[0], batchCount);
|
||||
GRID_ASSERT(st1 == CUBLAS_STATUS_SUCCESS);
|
||||
|
||||
// getri is OUT of place: hidden workspace keeps the surface in-place
|
||||
deviceVector<ComplexF> work((uint64_t)batchCount*N*N);
|
||||
deviceVector<ComplexF*> Cptr(batchCount);
|
||||
std::vector<ComplexF*> Cptr_h(batchCount);
|
||||
std::vector<ComplexF*> Aptr_h(batchCount);
|
||||
for(int i=0;i<batchCount;i++) Cptr_h[i] = &work[(uint64_t)i*N*N];
|
||||
acceleratorCopyToDevice(&Cptr_h[0],&Cptr[0],batchCount*sizeof(ComplexF*));
|
||||
acceleratorCopyFromDevice(&Amat[0],&Aptr_h[0],batchCount*sizeof(ComplexF*));
|
||||
|
||||
auto st2 = cublasCgetriBatched(Handle(), n,
|
||||
(const cuComplex *const *)&Amat[0], n,
|
||||
&ipiv[0],
|
||||
(cuComplex **)&Cptr[0], n,
|
||||
&info[0], batchCount);
|
||||
GRID_ASSERT(st2 == CUBLAS_STATUS_SUCCESS);
|
||||
accelerator_barrier();
|
||||
std::vector<int> info_h(batchCount);
|
||||
acceleratorCopyFromDevice(&info[0],&info_h[0],batchCount*sizeof(int));
|
||||
for(int i=0;i<batchCount;i++) GRID_ASSERT(info_h[i]==0);
|
||||
for(int i=0;i<batchCount;i++)
|
||||
acceleratorCopyDeviceToDevice(Cptr_h[i],Aptr_h[i],(uint64_t)N*N*sizeof(ComplexF));
|
||||
#endif
|
||||
#ifdef GRID_SYCL
|
||||
// Per-element oneMKL LAPACK on the in-order queue; group API optimisation later.
|
||||
sycl::queue *q = Handle();
|
||||
std::vector<ComplexF*> Aptr_h(batchCount);
|
||||
acceleratorCopyFromDevice(&Amat[0],&Aptr_h[0],batchCount*sizeof(ComplexF*));
|
||||
|
||||
int64_t lwf = oneapi::mkl::lapack::getrf_scratchpad_size<std::complex<float> >(*q,N,N,N);
|
||||
int64_t lwi = oneapi::mkl::lapack::getri_scratchpad_size<std::complex<float> >(*q,N,N);
|
||||
deviceVector<ComplexF> scratchf(lwf);
|
||||
deviceVector<ComplexF> scratchi(lwi);
|
||||
deviceVector<int64_t> ipiv(N);
|
||||
for(int i=0;i<batchCount;i++){
|
||||
oneapi::mkl::lapack::getrf(*q,N,N,(std::complex<float>*)Aptr_h[i],N,&ipiv[0],
|
||||
(std::complex<float>*)&scratchf[0],lwf);
|
||||
oneapi::mkl::lapack::getri(*q,N, (std::complex<float>*)Aptr_h[i],N,&ipiv[0],
|
||||
(std::complex<float>*)&scratchi[0],lwi);
|
||||
}
|
||||
q->wait();
|
||||
#endif
|
||||
#if !defined(GRID_SYCL) && !defined(GRID_CUDA) && !defined(GRID_HIP)
|
||||
// Reference implementation; the oracle the unit test locks semantics with.
|
||||
thread_for (p, batchCount, {
|
||||
Eigen::Map<Eigen::MatrixXcf> eA(Amat[p],N,N);
|
||||
Eigen::PartialPivLU<Eigen::MatrixXcf> lu(eA);
|
||||
eA = lu.inverse();
|
||||
});
|
||||
#endif
|
||||
}
|
||||
|
||||
void inverseBatched(int64_t N, deviceVector<ComplexD*> &Amat)
|
||||
{
|
||||
int32_t batchCount = Amat.size();
|
||||
GRID_ASSERT(batchCount > 0);
|
||||
|
||||
#ifdef GRID_HIP
|
||||
GRID_ASSERT( N < 2147483647L );
|
||||
rocblas_int n = (rocblas_int)N;
|
||||
rocblas_int lda = (rocblas_int)N;
|
||||
|
||||
deviceVector<rocblas_int> ipiv((uint64_t)batchCount*N);
|
||||
deviceVector<rocblas_int> info(batchCount);
|
||||
|
||||
auto st1 = rocsolver_zgetrf_batched(Handle(), n, n,
|
||||
(rocblas_double_complex *const *)&Amat[0], lda,
|
||||
&ipiv[0], (rocblas_stride)N,
|
||||
&info[0], batchCount);
|
||||
GRID_ASSERT(st1 == rocblas_status_success);
|
||||
auto st2 = rocsolver_zgetri_batched(Handle(), n,
|
||||
(rocblas_double_complex *const *)&Amat[0], lda,
|
||||
&ipiv[0], (rocblas_stride)N,
|
||||
&info[0], batchCount);
|
||||
GRID_ASSERT(st2 == rocblas_status_success);
|
||||
accelerator_barrier();
|
||||
std::vector<rocblas_int> info_h(batchCount);
|
||||
acceleratorCopyFromDevice(&info[0],&info_h[0],batchCount*sizeof(rocblas_int));
|
||||
for(int i=0;i<batchCount;i++) GRID_ASSERT(info_h[i]==0);
|
||||
#endif
|
||||
#ifdef GRID_CUDA
|
||||
GRID_ASSERT( N < 2147483647L );
|
||||
int n = (int)N;
|
||||
|
||||
deviceVector<int> ipiv((uint64_t)batchCount*N);
|
||||
deviceVector<int> info(batchCount);
|
||||
|
||||
auto st1 = cublasZgetrfBatched(Handle(), n,
|
||||
(cuDoubleComplex **)&Amat[0], n,
|
||||
&ipiv[0], &info[0], batchCount);
|
||||
GRID_ASSERT(st1 == CUBLAS_STATUS_SUCCESS);
|
||||
|
||||
deviceVector<ComplexD> work((uint64_t)batchCount*N*N);
|
||||
deviceVector<ComplexD*> Cptr(batchCount);
|
||||
std::vector<ComplexD*> Cptr_h(batchCount);
|
||||
std::vector<ComplexD*> Aptr_h(batchCount);
|
||||
for(int i=0;i<batchCount;i++) Cptr_h[i] = &work[(uint64_t)i*N*N];
|
||||
acceleratorCopyToDevice(&Cptr_h[0],&Cptr[0],batchCount*sizeof(ComplexD*));
|
||||
acceleratorCopyFromDevice(&Amat[0],&Aptr_h[0],batchCount*sizeof(ComplexD*));
|
||||
|
||||
auto st2 = cublasZgetriBatched(Handle(), n,
|
||||
(const cuDoubleComplex *const *)&Amat[0], n,
|
||||
&ipiv[0],
|
||||
(cuDoubleComplex **)&Cptr[0], n,
|
||||
&info[0], batchCount);
|
||||
GRID_ASSERT(st2 == CUBLAS_STATUS_SUCCESS);
|
||||
accelerator_barrier();
|
||||
std::vector<int> info_h(batchCount);
|
||||
acceleratorCopyFromDevice(&info[0],&info_h[0],batchCount*sizeof(int));
|
||||
for(int i=0;i<batchCount;i++) GRID_ASSERT(info_h[i]==0);
|
||||
for(int i=0;i<batchCount;i++)
|
||||
acceleratorCopyDeviceToDevice(Cptr_h[i],Aptr_h[i],(uint64_t)N*N*sizeof(ComplexD));
|
||||
#endif
|
||||
#ifdef GRID_SYCL
|
||||
sycl::queue *q = Handle();
|
||||
std::vector<ComplexD*> Aptr_h(batchCount);
|
||||
acceleratorCopyFromDevice(&Amat[0],&Aptr_h[0],batchCount*sizeof(ComplexD*));
|
||||
|
||||
int64_t lwf = oneapi::mkl::lapack::getrf_scratchpad_size<std::complex<double> >(*q,N,N,N);
|
||||
int64_t lwi = oneapi::mkl::lapack::getri_scratchpad_size<std::complex<double> >(*q,N,N);
|
||||
deviceVector<ComplexD> scratchf(lwf);
|
||||
deviceVector<ComplexD> scratchi(lwi);
|
||||
deviceVector<int64_t> ipiv(N);
|
||||
for(int i=0;i<batchCount;i++){
|
||||
oneapi::mkl::lapack::getrf(*q,N,N,(std::complex<double>*)Aptr_h[i],N,&ipiv[0],
|
||||
(std::complex<double>*)&scratchf[0],lwf);
|
||||
oneapi::mkl::lapack::getri(*q,N, (std::complex<double>*)Aptr_h[i],N,&ipiv[0],
|
||||
(std::complex<double>*)&scratchi[0],lwi);
|
||||
}
|
||||
q->wait();
|
||||
#endif
|
||||
#if !defined(GRID_SYCL) && !defined(GRID_CUDA) && !defined(GRID_HIP)
|
||||
thread_for (p, batchCount, {
|
||||
Eigen::Map<Eigen::MatrixXcd> eA(Amat[p],N,N);
|
||||
Eigen::PartialPivLU<Eigen::MatrixXcd> lu(eA);
|
||||
eA = lu.inverse();
|
||||
});
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -61,17 +61,6 @@ public:
|
||||
uint64_t coarse_vol;
|
||||
uint64_t words;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// Blocking geometry in full local coordinates. Addressing in lSites rather
|
||||
// than (lane,oSite) lets the fine and coarse spaces carry different SIMD
|
||||
// layouts, so an unvectorised coarse space may block a vectorised fine one.
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
Coordinate fine_ldimensions;
|
||||
Coordinate coarse_ldimensions;
|
||||
Coordinate block_ldimensions;
|
||||
Coordinate fine_simd;
|
||||
Coordinate coarse_simd;
|
||||
|
||||
// Row major layout "C" order:
|
||||
// BLAS_V[coarse_vol][nbasis][block_vol][words]
|
||||
// BLAS_F[coarse_vol][nrhs][block_vol][words]
|
||||
@@ -131,26 +120,9 @@ public:
|
||||
fine_vol = fine_grid->lSites();
|
||||
coarse_vol = coarse_grid->lSites();
|
||||
block_vol = fine_vol/coarse_vol;
|
||||
|
||||
|
||||
words = sizeof(scalar_object)/sizeof(scalar);
|
||||
|
||||
int nd = coarse_grid->_ndimension;
|
||||
GRID_ASSERT(fine_grid->_ndimension == nd);
|
||||
|
||||
fine_ldimensions.resize(nd);
|
||||
coarse_ldimensions.resize(nd);
|
||||
block_ldimensions.resize(nd);
|
||||
fine_simd = fine_grid->_simd_layout;
|
||||
coarse_simd = coarse_grid->_simd_layout;
|
||||
for(int d=0;d<nd;d++){
|
||||
GRID_ASSERT(fine_grid->_processors[d] == coarse_grid->_processors[d]);
|
||||
fine_ldimensions [d] = fine_grid->_rdimensions [d]*fine_grid->_simd_layout [d];
|
||||
coarse_ldimensions[d] = coarse_grid->_rdimensions[d]*coarse_grid->_simd_layout[d];
|
||||
block_ldimensions [d] = fine_ldimensions[d]/coarse_ldimensions[d];
|
||||
GRID_ASSERT(block_ldimensions[d]*coarse_ldimensions[d] == fine_ldimensions[d]);
|
||||
}
|
||||
GRID_ASSERT(block_vol == fine_vol/coarse_vol);
|
||||
|
||||
BLAS_V.resize (fine_vol * words * nbasis );
|
||||
}
|
||||
void ImportFineGridVectors(std::vector <Field > &vecs, deviceVector<scalar> &blas)
|
||||
@@ -161,16 +133,22 @@ public:
|
||||
|
||||
GRID_ASSERT(vecs[0].Grid()==fine_grid);
|
||||
|
||||
subdivides(coarse_grid,fine_grid); // require they map
|
||||
|
||||
int _ndimension = coarse_grid->_ndimension;
|
||||
GRID_ASSERT(block_vol == fine_grid->oSites() / coarse_grid->oSites());
|
||||
|
||||
Coordinate block_r (_ndimension);
|
||||
for(int d=0 ; d<_ndimension;d++){
|
||||
block_r[d] = fine_grid->_rdimensions[d] / coarse_grid->_rdimensions[d];
|
||||
}
|
||||
|
||||
uint64_t sz = blas.size();
|
||||
|
||||
acceleratorMemSet(&blas[0],0,blas.size()*sizeof(scalar));
|
||||
|
||||
Coordinate fine_rdimensions = fine_grid->_rdimensions;
|
||||
Coordinate coarse_l = coarse_ldimensions;
|
||||
Coordinate block_l = block_ldimensions;
|
||||
Coordinate fsimd = fine_simd;
|
||||
Coordinate coarse_rdimensions = coarse_grid->_rdimensions;
|
||||
int64_t bv= block_vol;
|
||||
for(int v=0;v<vecs.size();v++){
|
||||
|
||||
@@ -184,7 +162,9 @@ public:
|
||||
|
||||
// loop over fine sites
|
||||
const int Nsimd = vobj::Nsimd();
|
||||
GRID_ASSERT(sz == coarse_vol * block_vol * nvec * words);
|
||||
// std::cout << "sz "<<sz<<std::endl;
|
||||
// std::cout << "prod "<<Nsimd * coarse_grid->oSites() * block_vol * nvec * words<<std::endl;
|
||||
GRID_ASSERT(sz == Nsimd * coarse_grid->oSites() * block_vol * nvec * words);
|
||||
uint64_t lwords= words; // local variable for copy in to GPU
|
||||
accelerator_for(sf,osites,Nsimd,{
|
||||
#ifdef GRID_SIMT
|
||||
@@ -195,27 +175,27 @@ public:
|
||||
#endif
|
||||
// One thread per fine site
|
||||
Coordinate coor_f(_ndimension);
|
||||
Coordinate coor_l(_ndimension);
|
||||
Coordinate coor_b(_ndimension);
|
||||
Coordinate coor_c(_ndimension);
|
||||
|
||||
// Fine (oSite,lane) to full local coor
|
||||
// Fine site to fine coor
|
||||
Lexicographic::CoorFromIndex(coor_f,sf,fine_rdimensions);
|
||||
Lexicographic::CoorFromIndex(coor_l,lane,fsimd);
|
||||
for(int d=0;d<_ndimension;d++) coor_f[d] += fine_rdimensions[d]*coor_l[d];
|
||||
|
||||
for(int d=0;d<_ndimension;d++) coor_b[d] = coor_f[d]%block_l[d];
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] = coor_f[d]/block_l[d];
|
||||
|
||||
for(int d=0;d<_ndimension;d++) coor_b[d] = coor_f[d]%block_r[d];
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] = coor_f[d]/block_r[d];
|
||||
|
||||
int sc;// coarse site
|
||||
int sb;// block site
|
||||
Lexicographic::IndexFromCoor(coor_c,sc,coarse_l);
|
||||
Lexicographic::IndexFromCoor(coor_b,sb,block_l);
|
||||
Lexicographic::IndexFromCoor(coor_c,sc,coarse_rdimensions);
|
||||
Lexicographic::IndexFromCoor(coor_b,sb,block_r);
|
||||
|
||||
scalar_object data = extractLane(lane,fineData[sf]);
|
||||
|
||||
// BLAS_F[coarse_vol][nvec][block_vol][words]
|
||||
int64_t site = (sc*nvec + v)*bv
|
||||
// BLAS layout address calculation
|
||||
// words * block_vol * nbasis x coarse_vol
|
||||
// coarse oSite x block vole x lanes
|
||||
int64_t site = (lane*osites + sc*bv)*nvec
|
||||
+ v*bv
|
||||
+ sb;
|
||||
|
||||
// GRID_ASSERT(site*lwords<sz);
|
||||
@@ -233,318 +213,6 @@ public:
|
||||
// std::cout << " BlockProjector imported vector"<<v<<std::endl;
|
||||
}
|
||||
}
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// Import direct from multiRHS fine order, avoiding the unpack to a vector
|
||||
// of single RHS fields.
|
||||
//
|
||||
// fine mrhs grid : rhs is dimension 0, undistributed, unvectorised
|
||||
// Grid order : F[fine_vol][nrhs][words]
|
||||
// BLAS order : BLAS_F[lane][coarse_vol][nrhs][block_vol][words]
|
||||
//
|
||||
// The gather of block_vol from fine_vol, and the transpose of nrhs against
|
||||
// block_vol, are the irreducible part: this is not the identity.
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
void ImportFineGridMrhsVectors(Field &vec_mrhs, deviceVector<scalar> &blas)
|
||||
{
|
||||
typedef typename Field::vector_object vobj;
|
||||
|
||||
GridBase *fine_mrhs_grid = vec_mrhs.Grid();
|
||||
int _ndimension = coarse_grid->_ndimension;
|
||||
|
||||
GRID_ASSERT(fine_mrhs_grid->_ndimension == _ndimension+1);
|
||||
GRID_ASSERT(fine_mrhs_grid->_simd_layout[0] == 1);
|
||||
GRID_ASSERT(fine_mrhs_grid->_processors[0] == 1);
|
||||
for(int d=0;d<_ndimension;d++){
|
||||
GRID_ASSERT(fine_mrhs_grid->_rdimensions[d+1] == fine_grid->_rdimensions[d]);
|
||||
GRID_ASSERT(fine_mrhs_grid->_simd_layout[d+1] == fine_grid->_simd_layout[d]);
|
||||
}
|
||||
int nvec = fine_mrhs_grid->_rdimensions[0]; // nrhs
|
||||
|
||||
uint64_t sz = blas.size();
|
||||
acceleratorMemSet(&blas[0],0,blas.size()*sizeof(scalar));
|
||||
|
||||
Coordinate fine_mrhs_rdimensions = fine_mrhs_grid->_rdimensions;
|
||||
Coordinate fine_rdimensions = fine_grid->_rdimensions;
|
||||
Coordinate coarse_l = coarse_ldimensions;
|
||||
Coordinate block_l = block_ldimensions;
|
||||
Coordinate fsimd = fine_simd;
|
||||
int64_t bv= block_vol;
|
||||
|
||||
autoView( fineData , vec_mrhs, AcceleratorRead);
|
||||
auto blasData_p = &blas[0];
|
||||
auto fineData_p = &fineData[0];
|
||||
|
||||
int64_t osites = fine_grid->oSites(); // D dimensional
|
||||
int64_t osites_hi = fine_mrhs_grid->oSites(); // nvec * osites
|
||||
|
||||
const int Nsimd = vobj::Nsimd();
|
||||
GRID_ASSERT(sz == coarse_vol * block_vol * nvec * words);
|
||||
uint64_t lwords= words;
|
||||
int64_t lnvec = nvec;
|
||||
|
||||
accelerator_for(sfr,osites_hi,Nsimd,{
|
||||
#ifdef GRID_SIMT
|
||||
{
|
||||
int lane=acceleratorSIMTlane(Nsimd); // buffer lane
|
||||
#else
|
||||
for(int lane=0;lane<Nsimd;lane++) {
|
||||
#endif
|
||||
Coordinate coor_hi(_ndimension+1);
|
||||
Coordinate coor_f(_ndimension);
|
||||
Coordinate coor_l(_ndimension);
|
||||
Coordinate coor_b(_ndimension);
|
||||
Coordinate coor_c(_ndimension);
|
||||
|
||||
// rhs is dimension 0 of the D+1 grid
|
||||
Lexicographic::CoorFromIndex(coor_hi,sfr,fine_mrhs_rdimensions);
|
||||
int v = coor_hi[0];
|
||||
for(int d=0;d<_ndimension;d++) coor_f[d] = coor_hi[d+1];
|
||||
|
||||
Lexicographic::CoorFromIndex(coor_l,lane,fsimd);
|
||||
for(int d=0;d<_ndimension;d++) coor_f[d] += fine_rdimensions[d]*coor_l[d];
|
||||
|
||||
for(int d=0;d<_ndimension;d++) coor_b[d] = coor_f[d]%block_l[d];
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] = coor_f[d]/block_l[d];
|
||||
|
||||
int sc;// coarse site
|
||||
int sb;// block site
|
||||
Lexicographic::IndexFromCoor(coor_c,sc,coarse_l);
|
||||
Lexicographic::IndexFromCoor(coor_b,sb,block_l);
|
||||
|
||||
scalar_object data = extractLane(lane,fineData[sfr]);
|
||||
|
||||
int64_t site = (sc*lnvec + v)*bv
|
||||
+ sb;
|
||||
|
||||
scalar_object * ptr = (scalar_object *)&blasData_p[site*lwords];
|
||||
*ptr = data;
|
||||
#ifdef GRID_SIMT
|
||||
}
|
||||
#else
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// Export direct to multiRHS coarse order.
|
||||
//
|
||||
// Grid order : C[coarse_vol][nrhs][nbasis]
|
||||
// BLAS order : BLAS_C[lane][coarse_vol][nrhs][nbasis]
|
||||
//
|
||||
// At Nsimd()==1 these are the same sequence of addresses.
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
template<class vobj>
|
||||
void ExportCoarseGridMrhsVectors(Lattice<vobj> &vec_mrhs, deviceVector<scalar> &blas)
|
||||
{
|
||||
typedef typename vobj::scalar_object coarse_scalar_object;
|
||||
|
||||
GridBase *coarse_mrhs_grid = vec_mrhs.Grid();
|
||||
int _ndimension = coarse_grid->_ndimension;
|
||||
|
||||
GRID_ASSERT(coarse_mrhs_grid->_ndimension == _ndimension+1);
|
||||
GRID_ASSERT(coarse_mrhs_grid->_simd_layout[0] == 1);
|
||||
GRID_ASSERT(coarse_mrhs_grid->_processors[0] == 1);
|
||||
for(int d=0;d<_ndimension;d++){
|
||||
GRID_ASSERT(coarse_mrhs_grid->_rdimensions[d+1] == coarse_grid->_rdimensions[d]);
|
||||
GRID_ASSERT(coarse_mrhs_grid->_simd_layout[d+1] == coarse_grid->_simd_layout[d]);
|
||||
}
|
||||
int nvec = coarse_mrhs_grid->_rdimensions[0]; // nrhs
|
||||
|
||||
Coordinate coarse_mrhs_rdimensions = coarse_mrhs_grid->_rdimensions;
|
||||
Coordinate coarse_rdimensions = coarse_grid->_rdimensions;
|
||||
Coordinate coarse_l = coarse_ldimensions;
|
||||
Coordinate csimd = coarse_simd;
|
||||
|
||||
autoView( coarseData , vec_mrhs, AcceleratorWrite);
|
||||
auto blasData_p = &blas[0];
|
||||
auto coarseData_p = &coarseData[0];
|
||||
|
||||
int64_t osites = coarse_grid->oSites(); // D dimensional
|
||||
int64_t osites_hi = coarse_mrhs_grid->oSites(); // nvec * osites
|
||||
|
||||
const int Nsimd = vobj::Nsimd();
|
||||
uint64_t cwords=sizeof(typename vobj::scalar_object)/sizeof(scalar);
|
||||
GRID_ASSERT(cwords==nbasis);
|
||||
int64_t lnvec = nvec;
|
||||
|
||||
accelerator_for(scr,osites_hi,Nsimd,{
|
||||
#ifdef GRID_SIMT
|
||||
{
|
||||
int lane=acceleratorSIMTlane(Nsimd); // buffer lane
|
||||
#else
|
||||
for(int lane=0;lane<Nsimd;lane++) {
|
||||
#endif
|
||||
Coordinate coor_hi(_ndimension+1);
|
||||
Coordinate coor_l(_ndimension);
|
||||
Coordinate coor_c(_ndimension);
|
||||
|
||||
Lexicographic::CoorFromIndex(coor_hi,scr,coarse_mrhs_rdimensions);
|
||||
int v = coor_hi[0];
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] = coor_hi[d+1];
|
||||
|
||||
Lexicographic::CoorFromIndex(coor_l,lane,csimd);
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] += coarse_rdimensions[d]*coor_l[d];
|
||||
|
||||
int sc;
|
||||
Lexicographic::IndexFromCoor(coor_c,sc,coarse_l);
|
||||
|
||||
int64_t blas_site = (sc*lnvec + v)*cwords;
|
||||
coarse_scalar_object * ptr = (coarse_scalar_object *)&blasData_p[blas_site];
|
||||
coarse_scalar_object data = *ptr;
|
||||
insertLane(lane,coarseData[scr],data);
|
||||
#ifdef GRID_SIMT
|
||||
}
|
||||
#else
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// Reverse directions: BLAS_F -> fine mrhs field, coarse mrhs field -> BLAS_C
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
void ExportFineGridMrhsVectors(Field &vec_mrhs, deviceVector<scalar> &blas)
|
||||
{
|
||||
typedef typename Field::vector_object vobj;
|
||||
|
||||
GridBase *fine_mrhs_grid = vec_mrhs.Grid();
|
||||
int _ndimension = coarse_grid->_ndimension;
|
||||
|
||||
GRID_ASSERT(fine_mrhs_grid->_ndimension == _ndimension+1);
|
||||
GRID_ASSERT(fine_mrhs_grid->_simd_layout[0] == 1);
|
||||
for(int d=0;d<_ndimension;d++){
|
||||
GRID_ASSERT(fine_mrhs_grid->_rdimensions[d+1] == fine_grid->_rdimensions[d]);
|
||||
GRID_ASSERT(fine_mrhs_grid->_simd_layout[d+1] == fine_grid->_simd_layout[d]);
|
||||
}
|
||||
int nvec = fine_mrhs_grid->_rdimensions[0];
|
||||
|
||||
Coordinate fine_mrhs_rdimensions = fine_mrhs_grid->_rdimensions;
|
||||
Coordinate fine_rdimensions = fine_grid->_rdimensions;
|
||||
Coordinate coarse_l = coarse_ldimensions;
|
||||
Coordinate block_l = block_ldimensions;
|
||||
Coordinate fsimd = fine_simd;
|
||||
int64_t bv= block_vol;
|
||||
|
||||
autoView( fineData , vec_mrhs, AcceleratorWrite);
|
||||
auto blasData_p = &blas[0];
|
||||
auto fineData_p = &fineData[0];
|
||||
|
||||
int64_t osites = fine_grid->oSites();
|
||||
int64_t osites_hi = fine_mrhs_grid->oSites();
|
||||
|
||||
const int Nsimd = vobj::Nsimd();
|
||||
uint64_t lwords= words;
|
||||
int64_t lnvec = nvec;
|
||||
|
||||
accelerator_for(sfr,osites_hi,Nsimd,{
|
||||
#ifdef GRID_SIMT
|
||||
{
|
||||
int lane=acceleratorSIMTlane(Nsimd);
|
||||
#else
|
||||
for(int lane=0;lane<Nsimd;lane++) {
|
||||
#endif
|
||||
Coordinate coor_hi(_ndimension+1);
|
||||
Coordinate coor_f(_ndimension);
|
||||
Coordinate coor_l(_ndimension);
|
||||
Coordinate coor_b(_ndimension);
|
||||
Coordinate coor_c(_ndimension);
|
||||
|
||||
Lexicographic::CoorFromIndex(coor_hi,sfr,fine_mrhs_rdimensions);
|
||||
int v = coor_hi[0];
|
||||
for(int d=0;d<_ndimension;d++) coor_f[d] = coor_hi[d+1];
|
||||
|
||||
Lexicographic::CoorFromIndex(coor_l,lane,fsimd);
|
||||
for(int d=0;d<_ndimension;d++) coor_f[d] += fine_rdimensions[d]*coor_l[d];
|
||||
|
||||
for(int d=0;d<_ndimension;d++) coor_b[d] = coor_f[d]%block_l[d];
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] = coor_f[d]/block_l[d];
|
||||
|
||||
int sc,sb;
|
||||
Lexicographic::IndexFromCoor(coor_c,sc,coarse_l);
|
||||
Lexicographic::IndexFromCoor(coor_b,sb,block_l);
|
||||
|
||||
int64_t site = (sc*lnvec + v)*bv
|
||||
+ sb;
|
||||
|
||||
scalar_object * ptr = (scalar_object *)&blasData_p[site*lwords];
|
||||
scalar_object data = *ptr;
|
||||
insertLane(lane,fineData[sfr],data);
|
||||
#ifdef GRID_SIMT
|
||||
}
|
||||
#else
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
template<class vobj>
|
||||
void ImportCoarseGridMrhsVectors(Lattice<vobj> &vec_mrhs, deviceVector<scalar> &blas)
|
||||
{
|
||||
typedef typename vobj::scalar_object coarse_scalar_object;
|
||||
|
||||
GridBase *coarse_mrhs_grid = vec_mrhs.Grid();
|
||||
int _ndimension = coarse_grid->_ndimension;
|
||||
|
||||
GRID_ASSERT(coarse_mrhs_grid->_ndimension == _ndimension+1);
|
||||
GRID_ASSERT(coarse_mrhs_grid->_simd_layout[0] == 1);
|
||||
for(int d=0;d<_ndimension;d++){
|
||||
GRID_ASSERT(coarse_mrhs_grid->_rdimensions[d+1] == coarse_grid->_rdimensions[d]);
|
||||
GRID_ASSERT(coarse_mrhs_grid->_simd_layout[d+1] == coarse_grid->_simd_layout[d]);
|
||||
}
|
||||
int nvec = coarse_mrhs_grid->_rdimensions[0];
|
||||
|
||||
Coordinate coarse_mrhs_rdimensions = coarse_mrhs_grid->_rdimensions;
|
||||
Coordinate coarse_rdimensions = coarse_grid->_rdimensions;
|
||||
Coordinate coarse_l = coarse_ldimensions;
|
||||
Coordinate csimd = coarse_simd;
|
||||
|
||||
autoView( coarseData , vec_mrhs, AcceleratorRead);
|
||||
auto blasData_p = &blas[0];
|
||||
auto coarseData_p = &coarseData[0];
|
||||
|
||||
int64_t osites = coarse_grid->oSites();
|
||||
int64_t osites_hi = coarse_mrhs_grid->oSites();
|
||||
|
||||
const int Nsimd = vobj::Nsimd();
|
||||
uint64_t cwords=sizeof(typename vobj::scalar_object)/sizeof(scalar);
|
||||
GRID_ASSERT(cwords==nbasis);
|
||||
int64_t lnvec = nvec;
|
||||
|
||||
accelerator_for(scr,osites_hi,Nsimd,{
|
||||
#ifdef GRID_SIMT
|
||||
{
|
||||
int lane=acceleratorSIMTlane(Nsimd);
|
||||
#else
|
||||
for(int lane=0;lane<Nsimd;lane++) {
|
||||
#endif
|
||||
Coordinate coor_hi(_ndimension+1);
|
||||
Coordinate coor_l(_ndimension);
|
||||
Coordinate coor_c(_ndimension);
|
||||
|
||||
Lexicographic::CoorFromIndex(coor_hi,scr,coarse_mrhs_rdimensions);
|
||||
int v = coor_hi[0];
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] = coor_hi[d+1];
|
||||
|
||||
Lexicographic::CoorFromIndex(coor_l,lane,csimd);
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] += coarse_rdimensions[d]*coor_l[d];
|
||||
|
||||
int sc;
|
||||
Lexicographic::IndexFromCoor(coor_c,sc,coarse_l);
|
||||
|
||||
coarse_scalar_object data = extractLane(lane,coarseData[scr]);
|
||||
|
||||
int64_t blas_site = (sc*lnvec + v)*cwords;
|
||||
coarse_scalar_object * ptr = (coarse_scalar_object *)&blasData_p[blas_site];
|
||||
*ptr = data;
|
||||
#ifdef GRID_SIMT
|
||||
}
|
||||
#else
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
void ExportFineGridVectors(std::vector <Field> &vecs, deviceVector<scalar> &blas)
|
||||
{
|
||||
typedef typename Field::vector_object vobj;
|
||||
@@ -553,12 +221,17 @@ public:
|
||||
|
||||
GRID_ASSERT(vecs[0].Grid()==fine_grid);
|
||||
|
||||
int _ndimension = coarse_grid->_ndimension;
|
||||
subdivides(coarse_grid,fine_grid); // require they map
|
||||
|
||||
int _ndimension = coarse_grid->_ndimension;
|
||||
GRID_ASSERT(block_vol == fine_grid->oSites() / coarse_grid->oSites());
|
||||
|
||||
Coordinate block_r (_ndimension);
|
||||
for(int d=0 ; d<_ndimension;d++){
|
||||
block_r[d] = fine_grid->_rdimensions[d] / coarse_grid->_rdimensions[d];
|
||||
}
|
||||
Coordinate fine_rdimensions = fine_grid->_rdimensions;
|
||||
Coordinate coarse_l = coarse_ldimensions;
|
||||
Coordinate block_l = block_ldimensions;
|
||||
Coordinate fsimd = fine_simd;
|
||||
Coordinate coarse_rdimensions = coarse_grid->_rdimensions;
|
||||
|
||||
// std::cout << " export fine Blas norm "<<blasNorm2(blas)<<std::endl;
|
||||
|
||||
@@ -586,24 +259,23 @@ public:
|
||||
#endif
|
||||
// One thread per fine site
|
||||
Coordinate coor_f(_ndimension);
|
||||
Coordinate coor_l(_ndimension);
|
||||
Coordinate coor_b(_ndimension);
|
||||
Coordinate coor_c(_ndimension);
|
||||
|
||||
Lexicographic::CoorFromIndex(coor_f,sf,fine_rdimensions);
|
||||
Lexicographic::CoorFromIndex(coor_l,lane,fsimd);
|
||||
for(int d=0;d<_ndimension;d++) coor_f[d] += fine_rdimensions[d]*coor_l[d];
|
||||
|
||||
for(int d=0;d<_ndimension;d++) coor_b[d] = coor_f[d]%block_l[d];
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] = coor_f[d]/block_l[d];
|
||||
|
||||
for(int d=0;d<_ndimension;d++) coor_b[d] = coor_f[d]%block_r[d];
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] = coor_f[d]/block_r[d];
|
||||
|
||||
int sc;
|
||||
int sb;
|
||||
Lexicographic::IndexFromCoor(coor_c,sc,coarse_l);
|
||||
Lexicographic::IndexFromCoor(coor_b,sb,block_l);
|
||||
Lexicographic::IndexFromCoor(coor_c,sc,coarse_rdimensions);
|
||||
Lexicographic::IndexFromCoor(coor_b,sb,block_r);
|
||||
|
||||
// BLAS_F[coarse_vol][nvec][block_vol][words]
|
||||
int64_t site = (sc*nvec + v)*bv
|
||||
// BLAS layout address calculation
|
||||
// words * block_vol * nbasis x coarse_vol
|
||||
int64_t site = (lane*osites + sc*bv)*nvec
|
||||
+ v*bv
|
||||
+ sb;
|
||||
|
||||
scalar_object * ptr = (scalar_object *)&blasData_p[site*lwords];
|
||||
@@ -634,9 +306,7 @@ public:
|
||||
uint64_t sz = blas.size();
|
||||
|
||||
Coordinate coarse_rdimensions = coarse_grid->_rdimensions;
|
||||
Coordinate coarse_l = coarse_ldimensions;
|
||||
Coordinate csimd = coarse_simd;
|
||||
|
||||
|
||||
for(int v=0;v<vecs.size();v++){
|
||||
|
||||
// std::cout << " BlockProjector importing coarse vector"<<v<<" "<<norm2(vecs[v])<<std::endl;
|
||||
@@ -660,17 +330,8 @@ public:
|
||||
for(int lane=0;lane<Nsimd;lane++) {
|
||||
#endif
|
||||
// C_br per site
|
||||
Coordinate coor_c(_ndimension);
|
||||
Coordinate coor_l(_ndimension);
|
||||
Lexicographic::CoorFromIndex(coor_c,sc,coarse_rdimensions);
|
||||
Lexicographic::CoorFromIndex(coor_l,lane,csimd);
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] += coarse_rdimensions[d]*coor_l[d];
|
||||
|
||||
int scl;
|
||||
Lexicographic::IndexFromCoor(coor_c,scl,coarse_l);
|
||||
|
||||
int64_t blas_site = (scl*nvec + v)*cwords;
|
||||
|
||||
int64_t blas_site = (lane*osites + sc)*nvec*cwords + v*cwords;
|
||||
|
||||
coarse_scalar_object data = extractLane(lane,coarseData[sc]);
|
||||
|
||||
coarse_scalar_object * ptr = (coarse_scalar_object *)&blasData_p[blas_site];
|
||||
@@ -699,9 +360,7 @@ public:
|
||||
uint64_t sz = blas.size();
|
||||
|
||||
Coordinate coarse_rdimensions = coarse_grid->_rdimensions;
|
||||
Coordinate coarse_l = coarse_ldimensions;
|
||||
Coordinate csimd = coarse_simd;
|
||||
|
||||
|
||||
// std::cout << " export coarsee Blas norm "<<blasNorm2(blas)<<std::endl;
|
||||
for(int v=0;v<vecs.size();v++){
|
||||
|
||||
@@ -726,16 +385,7 @@ public:
|
||||
#else
|
||||
for(int lane=0;lane<Nsimd;lane++) {
|
||||
#endif
|
||||
Coordinate coor_c(_ndimension);
|
||||
Coordinate coor_l(_ndimension);
|
||||
Lexicographic::CoorFromIndex(coor_c,sc,coarse_rdimensions);
|
||||
Lexicographic::CoorFromIndex(coor_l,lane,csimd);
|
||||
for(int d=0;d<_ndimension;d++) coor_c[d] += coarse_rdimensions[d]*coor_l[d];
|
||||
|
||||
int scl;
|
||||
Lexicographic::IndexFromCoor(coor_c,scl,coarse_l);
|
||||
|
||||
int64_t blas_site = (scl*nvec + v)*cwords;
|
||||
int64_t blas_site = (lane*osites + sc)*nvec*cwords + v*cwords;
|
||||
coarse_scalar_object * ptr = (coarse_scalar_object *)&blasData_p[blas_site];
|
||||
coarse_scalar_object data = *ptr;
|
||||
insertLane(lane,coarseData[sc],data);
|
||||
@@ -858,168 +508,6 @@ public:
|
||||
ExportFineGridVectors(fine, BLAS_F);
|
||||
// std::cout << " exported "<<std::endl;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// multiRHS ordered interfaces. The GEMM is identical; only the import and
|
||||
// export differ, so those are the whole of the layout question.
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
template<class cobj>
|
||||
void blockProject(Field &fine_mrhs,Lattice<cobj> &coarse_mrhs)
|
||||
{
|
||||
int nrhs = fine_mrhs.Grid()->_rdimensions[0];
|
||||
int _nbasis = sizeof(typename cobj::scalar_object)/sizeof(scalar);
|
||||
GRID_ASSERT(nbasis==_nbasis);
|
||||
GRID_ASSERT(coarse_mrhs.Grid()->_rdimensions[0]==nrhs);
|
||||
|
||||
BLAS_F.resize (fine_vol * words * nrhs );
|
||||
BLAS_C.resize (coarse_vol * nbasis * nrhs );
|
||||
|
||||
ImportFineGridMrhsVectors(fine_mrhs,BLAS_F);
|
||||
ProjectBLAS(nrhs);
|
||||
ExportCoarseGridMrhsVectors(coarse_mrhs,BLAS_C);
|
||||
}
|
||||
|
||||
template<class cobj>
|
||||
void blockPromote(Field &fine_mrhs,Lattice<cobj> &coarse_mrhs)
|
||||
{
|
||||
int nrhs = fine_mrhs.Grid()->_rdimensions[0];
|
||||
int _nbasis = sizeof(typename cobj::scalar_object)/sizeof(scalar);
|
||||
GRID_ASSERT(nbasis==_nbasis);
|
||||
GRID_ASSERT(coarse_mrhs.Grid()->_rdimensions[0]==nrhs);
|
||||
|
||||
BLAS_F.resize (fine_vol * words * nrhs );
|
||||
BLAS_C.resize (coarse_vol * nbasis * nrhs );
|
||||
|
||||
ImportCoarseGridMrhsVectors(coarse_mrhs,BLAS_C);
|
||||
PromoteBLAS(nrhs);
|
||||
ExportFineGridMrhsVectors(fine_mrhs,BLAS_F);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// Mixed orderings. A single RHS fine operator produces a vector of fine
|
||||
// fields with no packing; the coarse side is still wanted in mrhs order.
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
template<class cobj>
|
||||
void blockProject(std::vector<Field> &fine,Lattice<cobj> &coarse_mrhs)
|
||||
{
|
||||
int nrhs = fine.size();
|
||||
int _nbasis = sizeof(typename cobj::scalar_object)/sizeof(scalar);
|
||||
GRID_ASSERT(nbasis==_nbasis);
|
||||
GRID_ASSERT(coarse_mrhs.Grid()->_rdimensions[0]==nrhs);
|
||||
|
||||
BLAS_F.resize (fine_vol * words * nrhs );
|
||||
BLAS_C.resize (coarse_vol * nbasis * nrhs );
|
||||
|
||||
ImportFineGridVectors(fine,BLAS_F);
|
||||
ProjectBLAS(nrhs);
|
||||
ExportCoarseGridMrhsVectors(coarse_mrhs,BLAS_C);
|
||||
}
|
||||
|
||||
template<class cobj>
|
||||
void blockProject(Field &fine_mrhs,std::vector< Lattice<cobj> > &coarse)
|
||||
{
|
||||
int nrhs = fine_mrhs.Grid()->_rdimensions[0];
|
||||
int _nbasis = sizeof(typename cobj::scalar_object)/sizeof(scalar);
|
||||
GRID_ASSERT(nbasis==_nbasis);
|
||||
GRID_ASSERT(coarse.size()==nrhs);
|
||||
|
||||
BLAS_F.resize (fine_vol * words * nrhs );
|
||||
BLAS_C.resize (coarse_vol * nbasis * nrhs );
|
||||
|
||||
ImportFineGridMrhsVectors(fine_mrhs,BLAS_F);
|
||||
ProjectBLAS(nrhs);
|
||||
ExportCoarseGridVectors(coarse,BLAS_C);
|
||||
}
|
||||
|
||||
template<class cobj>
|
||||
void blockPromote(std::vector<Field> &fine,Lattice<cobj> &coarse_mrhs)
|
||||
{
|
||||
int nrhs = fine.size();
|
||||
int _nbasis = sizeof(typename cobj::scalar_object)/sizeof(scalar);
|
||||
GRID_ASSERT(nbasis==_nbasis);
|
||||
GRID_ASSERT(coarse_mrhs.Grid()->_rdimensions[0]==nrhs);
|
||||
|
||||
BLAS_F.resize (fine_vol * words * nrhs );
|
||||
BLAS_C.resize (coarse_vol * nbasis * nrhs );
|
||||
|
||||
ImportCoarseGridMrhsVectors(coarse_mrhs,BLAS_C);
|
||||
PromoteBLAS(nrhs);
|
||||
ExportFineGridVectors(fine,BLAS_F);
|
||||
}
|
||||
|
||||
template<class cobj>
|
||||
void blockPromote(Field &fine_mrhs,std::vector< Lattice<cobj> > &coarse)
|
||||
{
|
||||
int nrhs = fine_mrhs.Grid()->_rdimensions[0];
|
||||
int _nbasis = sizeof(typename cobj::scalar_object)/sizeof(scalar);
|
||||
GRID_ASSERT(nbasis==_nbasis);
|
||||
GRID_ASSERT(coarse.size()==nrhs);
|
||||
|
||||
BLAS_F.resize (fine_vol * words * nrhs );
|
||||
BLAS_C.resize (coarse_vol * nbasis * nrhs );
|
||||
|
||||
ImportCoarseGridVectors(coarse,BLAS_C);
|
||||
PromoteBLAS(nrhs);
|
||||
ExportFineGridMrhsVectors(fine_mrhs,BLAS_F);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// Pointer tables and the batched GEMM, shared by both orderings
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
void BLASPointers(int nrhs,
|
||||
deviceVector<scalar *> &Vd,
|
||||
deviceVector<scalar *> &Fd,
|
||||
deviceVector<scalar *> &Cd)
|
||||
{
|
||||
for(int c=0;c<coarse_vol;c++){
|
||||
scalar * Vh = & BLAS_V[c*nbasis*block_vol*words];
|
||||
scalar * Fh = & BLAS_F[c*nrhs*block_vol*words];
|
||||
scalar * Ch = & BLAS_C[c*nrhs*nbasis];
|
||||
acceleratorPut(Vd[c],Vh);
|
||||
acceleratorPut(Fd[c],Fh);
|
||||
acceleratorPut(Cd[c],Ch);
|
||||
}
|
||||
}
|
||||
|
||||
// C_br = V^dag F
|
||||
void ProjectBLAS(int nrhs)
|
||||
{
|
||||
deviceVector<scalar *> Vd(coarse_vol);
|
||||
deviceVector<scalar *> Fd(coarse_vol);
|
||||
deviceVector<scalar *> Cd(coarse_vol);
|
||||
BLASPointers(nrhs,Vd,Fd,Cd);
|
||||
|
||||
GridBLAS BLAS;
|
||||
int64_t vw = block_vol * words;
|
||||
BLAS.gemmBatched(GridBLAS_OP_C,GridBLAS_OP_N,
|
||||
nbasis,nrhs,vw,
|
||||
scalar(1.0),
|
||||
Vd,
|
||||
Fd,
|
||||
scalar(0.0), // wipe out C
|
||||
Cd);
|
||||
BLAS.synchronise();
|
||||
}
|
||||
|
||||
// F_xr = Vxb Cbr
|
||||
void PromoteBLAS(int nrhs)
|
||||
{
|
||||
deviceVector<scalar *> Vd(coarse_vol);
|
||||
deviceVector<scalar *> Fd(coarse_vol);
|
||||
deviceVector<scalar *> Cd(coarse_vol);
|
||||
BLASPointers(nrhs,Vd,Fd,Cd);
|
||||
|
||||
GridBLAS BLAS;
|
||||
int64_t vw = block_vol * words;
|
||||
BLAS.gemmBatched(GridBLAS_OP_N,GridBLAS_OP_N,
|
||||
vw,nrhs,nbasis,
|
||||
scalar(1.0),
|
||||
Vd,
|
||||
Cd,
|
||||
scalar(0.0), // wipe out F
|
||||
Fd);
|
||||
BLAS.synchronise();
|
||||
}
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -53,22 +53,7 @@ class TwoLevelCG : public LinearFunction<Field>
|
||||
// Fine operator, Smoother, CoarseSolver
|
||||
LinearOperatorBase<Field> &_FineLinop;
|
||||
LinearFunction<Field> &_Smoother;
|
||||
|
||||
GridStopWatch ProjectTimer;
|
||||
GridStopWatch PromoteTimer;
|
||||
GridStopWatch CoarseTimer;
|
||||
GridStopWatch SmoothTimer;
|
||||
GridStopWatch MatrixTimer;
|
||||
GridStopWatch M3Timer;
|
||||
GridStopWatch LinalgTimer;
|
||||
|
||||
int64_t M3Calls;
|
||||
int64_t SmoothCalls;
|
||||
int64_t MatrixCalls;
|
||||
int64_t ProjectCalls;
|
||||
int64_t CoarseCalls;
|
||||
int64_t PromoteCalls;
|
||||
|
||||
|
||||
// more most opertor functions
|
||||
TwoLevelCG(RealD tol,
|
||||
Integer maxit,
|
||||
@@ -118,20 +103,12 @@ class TwoLevelCG : public LinearFunction<Field>
|
||||
RealD tn;
|
||||
|
||||
GridStopWatch HDCGTimer;
|
||||
ProjectTimer.Reset();
|
||||
PromoteTimer.Reset();
|
||||
CoarseTimer.Reset();
|
||||
SmoothTimer.Reset();
|
||||
MatrixTimer.Reset();
|
||||
M3Timer.Reset();
|
||||
LinalgTimer.Reset();
|
||||
M3Calls = SmoothCalls = MatrixCalls = ProjectCalls = CoarseCalls = PromoteCalls = 0;
|
||||
HDCGTimer.Start();
|
||||
//////////////////////////
|
||||
// x0 = Vstart -- possibly modify guess
|
||||
//////////////////////////
|
||||
Vstart(x,src);
|
||||
|
||||
|
||||
// r0 = b -A x0
|
||||
_FineLinop.HermOp(x,mmp[0]);
|
||||
axpy (r, -1.0,mmp[0], src); // Recomputes r=src-Ax0
|
||||
@@ -168,40 +145,33 @@ class TwoLevelCG : public LinearFunction<Field>
|
||||
int peri_kp = (k+1) % mmax;
|
||||
|
||||
rtz=rtzp;
|
||||
M3Timer.Start();
|
||||
d= PcgM3(p[peri_k],mmp[peri_k]);
|
||||
M3Timer.Stop();
|
||||
M3Calls++;
|
||||
a = rtz/d;
|
||||
|
||||
|
||||
// Memorise this
|
||||
pAp[peri_k] = d;
|
||||
|
||||
LinalgTimer.Start();
|
||||
|
||||
axpy(x,a,p[peri_k],x);
|
||||
RealD rn = axpy_norm(r,-a,mmp[peri_k],r);
|
||||
LinalgTimer.Stop();
|
||||
|
||||
// Compute z = M x
|
||||
PcgM1(r,z);
|
||||
|
||||
|
||||
{
|
||||
RealD n1,n2;
|
||||
n1=norm2(r);
|
||||
n2=norm2(z);
|
||||
std::cout << GridLogMessage<<"HDCG::fPcg iteration "<<k<<" : vector r,z "<<n1<<" "<<n2<<"\n";
|
||||
}
|
||||
LinalgTimer.Start();
|
||||
rtzp =real(innerProduct(r,z));
|
||||
LinalgTimer.Stop();
|
||||
std::cout << GridLogMessage<<"HDCG::fPcg iteration "<<k<<" : inner rtzp "<<rtzp<<"\n";
|
||||
|
||||
// PcgM2(z,p[0]);
|
||||
PcgM2(z,mu); // ADEF-2 this is identity. Axpy possible to eliminate
|
||||
|
||||
|
||||
p[peri_kp]=mu;
|
||||
|
||||
// Standard search direction p -> z + b p
|
||||
// Standard search direction p -> z + b p
|
||||
b = (rtzp)/rtz;
|
||||
|
||||
int northog;
|
||||
@@ -232,25 +202,8 @@ class TwoLevelCG : public LinearFunction<Field>
|
||||
if ( rn <= rsq ) {
|
||||
|
||||
HDCGTimer.Stop();
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg converged in "<<k<<" iterations and "<<HDCGTimer.Elapsed()<<std::endl;
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg breakdown"<<std::endl;
|
||||
auto mspc = [](GridStopWatch &sw, int64_t n) -> double {
|
||||
return (n > 0) ? sw.useconds() * 1e-3 / n : 0.0;
|
||||
};
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg M3 (fine MVM) "<<M3Timer.Elapsed()
|
||||
<<" "<<M3Calls<<" calls "<<mspc(M3Timer,M3Calls)<<" ms/call"<<std::endl;
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg linalg "<<LinalgTimer.Elapsed()<<std::endl;
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg smoother "<<SmoothTimer.Elapsed()
|
||||
<<" "<<SmoothCalls<<" calls "<<mspc(SmoothTimer,SmoothCalls)<<" ms/call"<<std::endl;
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg matrix (in M1) "<<MatrixTimer.Elapsed()
|
||||
<<" "<<MatrixCalls<<" calls "<<mspc(MatrixTimer,MatrixCalls)<<" ms/call"<<std::endl;
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg project "<<ProjectTimer.Elapsed()
|
||||
<<" "<<ProjectCalls<<" calls "<<mspc(ProjectTimer,ProjectCalls)<<" ms/call"<<std::endl;
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg coarse "<<CoarseTimer.Elapsed()
|
||||
<<" "<<CoarseCalls<<" calls "<<mspc(CoarseTimer,CoarseCalls)<<" ms/call"<<std::endl;
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg promote "<<PromoteTimer.Elapsed()
|
||||
<<" "<<PromoteCalls<<" calls "<<mspc(PromoteTimer,PromoteCalls)<<" ms/call"<<std::endl;
|
||||
|
||||
std::cout<<GridLogMessage<<"HDCG: fPcg converged in "<<k<<" iterations and "<<HDCGTimer.Elapsed()<<std::endl;;
|
||||
|
||||
_FineLinop.HermOp(x,mmp[0]);
|
||||
axpy(tmp,-1.0,src,mmp[0]);
|
||||
|
||||
@@ -522,29 +475,35 @@ class TwoLevelADEF2 : public TwoLevelCG<Field>
|
||||
CoarseField PleftProj(this->coarsegrid);
|
||||
CoarseField PleftMss_proj(this->coarsegrid);
|
||||
|
||||
this->SmoothTimer.Start();
|
||||
GridStopWatch SmootherTimer;
|
||||
GridStopWatch MatrixTimer;
|
||||
SmootherTimer.Start();
|
||||
this->_Smoother(in,Min);
|
||||
this->SmoothTimer.Stop();
|
||||
this->SmoothCalls++;
|
||||
SmootherTimer.Stop();
|
||||
|
||||
this->MatrixTimer.Start();
|
||||
MatrixTimer.Start();
|
||||
this->_FineLinop.HermOp(Min,out);
|
||||
this->MatrixTimer.Stop();
|
||||
this->MatrixCalls++;
|
||||
MatrixTimer.Stop();
|
||||
axpy(tmp,-1.0,out,in); // tmp = in - A Min
|
||||
|
||||
this->ProjectTimer.Start();
|
||||
this->_Aggregates.ProjectToSubspace(PleftProj,tmp);
|
||||
this->ProjectTimer.Stop();
|
||||
this->ProjectCalls++;
|
||||
this->CoarseTimer.Start();
|
||||
GridStopWatch ProjTimer;
|
||||
GridStopWatch CoarseTimer;
|
||||
GridStopWatch PromTimer;
|
||||
ProjTimer.Start();
|
||||
this->_Aggregates.ProjectToSubspace(PleftProj,tmp);
|
||||
ProjTimer.Stop();
|
||||
CoarseTimer.Start();
|
||||
this->_CoarseSolver(PleftProj,PleftMss_proj); // Ass^{-1} [in - A Min]_s
|
||||
this->CoarseTimer.Stop();
|
||||
this->CoarseCalls++;
|
||||
this->PromoteTimer.Start();
|
||||
this->_Aggregates.PromoteFromSubspace(PleftMss_proj,tmp);// tmp = Q[in - A Min]
|
||||
this->PromoteTimer.Stop();
|
||||
this->PromoteCalls++;
|
||||
CoarseTimer.Stop();
|
||||
PromTimer.Start();
|
||||
this->_Aggregates.PromoteFromSubspace(PleftMss_proj,tmp);// tmp = Q[in - A Min]
|
||||
PromTimer.Stop();
|
||||
std::cout << GridLogPerformance << "PcgM1 breakdown "<<std::endl;
|
||||
std::cout << GridLogPerformance << "\tSmoother " << SmootherTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\tMatrix " << MatrixTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\tProj " << ProjTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\tCoarse " << CoarseTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\tProm " << PromTimer.Elapsed() <<std::endl;
|
||||
|
||||
axpy(out,1.0,Min,tmp); // Min+tmp
|
||||
}
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/iterative/Arnoldi.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Peter Boyle <paboyle@ph.ed.ac.uk>
|
||||
Author: paboyle <paboyle@ph.ed.ac.uk>
|
||||
Author: Patrick Oare <poare@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_ARNOLDI_H
|
||||
#define GRID_ARNOLDI_H
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
//Moved to KrylovSchur
|
||||
#if 0
|
||||
/**
|
||||
<<<<<<< HEAD
|
||||
* Options for which Ritz values to keep in implicit restart.
|
||||
*/
|
||||
enum RitzFilter {
|
||||
EvalNormSmall, // Keep evals with smallest norm
|
||||
EvalNormLarge, // Keep evals with largest norm
|
||||
EvalReSmall, // Keep evals with smallest real part
|
||||
EvalReLarge // Keep evals with largest real part
|
||||
};
|
||||
|
||||
// Select comparison function from RitzFilter
|
||||
struct ComplexComparator
|
||||
{
|
||||
RitzFilter f;
|
||||
ComplexComparator (RitzFilter _f) : f(_f) {}
|
||||
bool operator()(std::complex<double> z1, std::complex<double> z2) {
|
||||
switch (f) {
|
||||
RealD tmp1, tmp2;
|
||||
tmp1=std::abs(std::imag(z1));
|
||||
tmp2=std::abs(std::imag(z2));
|
||||
case EvalNormSmall:
|
||||
return std::abs(z1) < std::abs(z2);
|
||||
case EvalNormLarge:
|
||||
return std::abs(z1) > std::abs(z2);
|
||||
// Terrible hack
|
||||
// return std::abs(std::real(z1)) < std::abs(std::real(z2));
|
||||
// if ( std::abs(std::real(z1)) >4.) tmp1 +=1.;
|
||||
// if ( std::abs(std::real(z2)) >4.) tmp2 +=1.;
|
||||
case EvalReSmall:
|
||||
return tmp1 < tmp2;
|
||||
// return std::abs(std::imag(z1)) < std::abs(std::imag(z2));
|
||||
case EvalReLarge:
|
||||
return tmp1 > tmp2;
|
||||
// return std::abs(std::real(z1)) > std::abs(std::real(z2));
|
||||
default:
|
||||
assert(0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
=======
|
||||
>>>>>>> 68af1bba67dd62881ead5ab1e54962a5486a0791
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Implementation of the Arnoldi algorithm.
|
||||
*/
|
||||
template<class Field>
|
||||
class Arnoldi {
|
||||
|
||||
private:
|
||||
|
||||
std::string cname = std::string("Arnoldi");
|
||||
int MaxIter; // Max iterations
|
||||
RealD Tolerance;
|
||||
RealD ssq;
|
||||
RealD rtol;
|
||||
int Nm; // Number of basis vectors to track (equals MaxIter if no restart)
|
||||
int Nk; // Number of basis vectors to keep every restart (equals -1 if no restart)
|
||||
int Nstop; // Stop after converging Nstop eigenvectors.
|
||||
|
||||
LinearOperatorBase<Field> &Linop;
|
||||
GridBase *Grid;
|
||||
|
||||
RealD approxLambdaMax;
|
||||
RealD beta_k;
|
||||
Field f;
|
||||
std::vector<Field> basis; // orthonormal Arnoldi basis
|
||||
Eigen::MatrixXcd Hess; // Hessenberg matrix of size Nbasis (after construction)
|
||||
Eigen::MatrixXcd Qt; // Transpose of basis rotation which projects out high modes.
|
||||
|
||||
Eigen::VectorXcd evals; // evals of Hess
|
||||
Eigen::MatrixXcd littleEvecs; // Nm x Nm evecs matrix
|
||||
std::vector<Field> evecs; // Vector of evec fields
|
||||
|
||||
RitzFilter ritzFilter; // how to sort evals
|
||||
|
||||
public:
|
||||
|
||||
Arnoldi(LinearOperatorBase<Field> &_Linop, GridBase *_Grid, RealD _Tolerance, RitzFilter filter = EvalReSmall)
|
||||
: Linop(_Linop), Grid(_Grid), Tolerance(_Tolerance), ritzFilter(filter), f(_Grid), MaxIter(-1), Nm(-1), Nk(-1),
|
||||
Nstop (-1), evals (0), evecs (), ssq (0.0), rtol (0.0), beta_k (0.0), approxLambdaMax (0.0)
|
||||
{
|
||||
f = Zero();
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs the Arnoldi loop with(out) implicit restarting. For each iteration:
|
||||
* - Runs an Arnoldi step.
|
||||
* - Computes the eigensystem of the Hessenberg matrix.
|
||||
* - Performs implicit restarting.
|
||||
*/
|
||||
void operator()(const Field& v0, int _maxIter, int _Nm, int _Nk, int _Nstop, bool doubleOrthog = false) {
|
||||
MaxIter = _maxIter;
|
||||
Nm = _Nm; Nk = _Nk;
|
||||
Nstop = _Nstop;
|
||||
|
||||
ssq = norm2(v0);
|
||||
RealD approxLambdaMax = approxMaxEval(v0);
|
||||
rtol = Tolerance * approxLambdaMax;
|
||||
|
||||
ComplexComparator compareComplex (ritzFilter);
|
||||
std::cout << GridLogMessage << "Comparing Ritz values with: " << ritzFilter << std::endl;
|
||||
|
||||
int start = 1;
|
||||
Field startVec = v0;
|
||||
littleEvecs = Eigen::MatrixXcd::Zero(Nm, Nm);
|
||||
for (int i = 0; i < MaxIter; i++) {
|
||||
std::cout << GridLogMessage << "Restart Iteration " << i << std::endl;
|
||||
|
||||
// Perform Arnoldi steps to compute Krylov basis and Rayleigh quotient (Hess)
|
||||
arnoldiIteration(startVec, Nm, start, doubleOrthog);
|
||||
startVec = f;
|
||||
|
||||
// compute eigensystem and sort evals
|
||||
// compute_eigensystem();
|
||||
compute_eigensystem(Hess);
|
||||
std::cout << GridLogMessage << "Eigenvalues after Arnoldi step: " << std::endl << evals << std::endl;
|
||||
|
||||
std::sort(evals.begin(), evals.end(), compareComplex);
|
||||
std::cout << GridLogMessage << "Ritz values after sorting (first Nk preserved): " << std::endl << evals << std::endl;
|
||||
// SU(N)::tepidConfiguration
|
||||
|
||||
// Implicit restart to de-weight unwanted eigenvalues
|
||||
implicitRestart(_Nm, _Nk); // probably can delete _Nm and _Nk from function args
|
||||
start = Nk;
|
||||
|
||||
// check convergence and return if needed.
|
||||
int Nconv = converged();
|
||||
std::cout << GridLogMessage << "Number of evecs converged: " << Nconv << std::endl;
|
||||
if (Nconv >= Nstop || i == MaxIter - 1) {
|
||||
std::cout << GridLogMessage << "Converged with " << Nconv << " / " << Nstop << " eigenvectors on iteration "
|
||||
<< i << "." << std::endl;
|
||||
basisRotate(evecs, Qt, 0, Nk, 0, Nk, Nm);
|
||||
std::cout << GridLogMessage << "Eigenvalues [first " << Nconv << " converged]: " << std::endl << evals << std::endl;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximates the maximum eigenvalue of Linop.Op to normalize the residual and test for convergence.
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* Field& v0
|
||||
* Source field to start with. Must have non-zero norm.
|
||||
* int MAX_ITER (default = 50)
|
||||
* Maximum number of iterations for power approximation.
|
||||
*
|
||||
* Returns
|
||||
* -------
|
||||
* RealD lamApprox
|
||||
* Approximation of largest eigenvalue.
|
||||
*/
|
||||
RealD approxMaxEval(const Field& v0, int MAX_ITER = 50) {
|
||||
assert (norm2(v0) > 1e-8); // must have relatively large source norm to start
|
||||
RealD lamApprox = 0.0;
|
||||
RealD denom = 1.0; RealD num = 1.0;
|
||||
Field v0cp (Grid); Field tmp (Grid);
|
||||
v0cp = v0;
|
||||
denom = std::sqrt(norm2(v0cp));
|
||||
for (int i = 0; i < MAX_ITER; i++) {
|
||||
Linop.Op(v0cp, tmp); // CAREFUL: do not do Op(tmp, tmp)
|
||||
v0cp = tmp;
|
||||
num = std::sqrt(norm2(v0cp)); // num = |A^{n+1} v0|
|
||||
lamApprox = num / denom; // lam = |A^{n+1} v0| / |A^n v0|
|
||||
std::cout << GridLogDebug << "Approx for max eval: " << lamApprox << std::endl;
|
||||
denom = num; // denom = |A^{n} v0|
|
||||
}
|
||||
return lamApprox;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs the Arnoldi basis for the Krylov space K_n(D, src). (TODO make private)
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* v0 : Field&
|
||||
* Source to generate Krylov basis.
|
||||
* Nm : int
|
||||
* Final size of the basis desired. If the basis becomes complete before a basis of size Nm is constructed
|
||||
* (determined by relative tolerance Tolerance), stops iteration there.
|
||||
* doubleOrthog : bool (default = false)
|
||||
* Whether to double orthogonalize the basis (for numerical cancellations) or not.
|
||||
* start : int (default = 0)
|
||||
* If non-zero, assumes part of the Arnoldi basis has already been constructed.
|
||||
*/
|
||||
void arnoldiIteration(const Field& v0, int Nm, int start = 1, bool doubleOrthog = false)
|
||||
{
|
||||
|
||||
ComplexD coeff;
|
||||
Field w (Grid); // A acting on last Krylov vector.
|
||||
|
||||
if (start == 1) { // initialize everything that we need.
|
||||
RealD v0Norm = 1 / std::sqrt(ssq);
|
||||
basis.push_back(v0Norm * v0); // normalized source
|
||||
|
||||
Hess = Eigen::MatrixXcd::Zero(Nm, Nm);
|
||||
f = Zero();
|
||||
} else {
|
||||
assert( start == basis.size() ); // should be starting at the end of basis (start = Nk)
|
||||
Eigen::MatrixXcd HessCp = Hess;
|
||||
Hess = Eigen::MatrixXcd::Zero(Nm, Nm);
|
||||
Hess(Eigen::seqN(0, Nk), Eigen::seqN(0, Nk)) = HessCp;
|
||||
}
|
||||
|
||||
// Construct next Arnoldi vector by normalizing w_i = Dv_i - \sum_j v_j h_{ji}
|
||||
for (int i = start - 1; i < Nm; i++) {
|
||||
|
||||
Linop.Op(basis.back(), w);
|
||||
for (int j = 0; j < basis.size(); j++) {
|
||||
coeff = innerProduct(basis[j], w); // coeff = h_{ij}. Note that since {vi} is ONB it's OK to subtract it off after.
|
||||
Hess(j, i) = coeff;
|
||||
w -= coeff * basis[j];
|
||||
}
|
||||
|
||||
if (doubleOrthog) {
|
||||
// TODO implement
|
||||
}
|
||||
|
||||
// add w_i to the pile
|
||||
if (i < Nm - 1) {
|
||||
coeff = std::sqrt(norm2(w));
|
||||
Hess(i+1, i) = coeff;
|
||||
basis.push_back(
|
||||
(1.0/coeff) * w
|
||||
);
|
||||
}
|
||||
|
||||
// after iterations, update f and beta_k = ||f||
|
||||
f = w; // make sure f is not normalized
|
||||
beta_k = std::sqrt(norm2(f)); // beta_k = ||f_k|| determines convergence.
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage << "|f|^2 after Arnoldi step = " << norm2(f) << std::endl;
|
||||
std::cout << GridLogDebug << "Computed Hessenberg matrix = " << std::endl << Hess << std::endl;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximates the eigensystem of the linear operator by computing the eigensystem of
|
||||
* the Hessenberg matrix. Assumes that the Hessenberg matrix has already been constructed (by
|
||||
* calling the operator() function).
|
||||
*
|
||||
* TODO implement in parent class eventually.
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* Eigen::MatrixXcd& S
|
||||
* Schur matrix (upper triangular) similar to original Rayleigh quotient.
|
||||
*/
|
||||
void compute_eigensystem(Eigen::MatrixXcd& S)
|
||||
{
|
||||
|
||||
std::cout << GridLogMessage << "Computing eigenvalues." << std::endl;
|
||||
|
||||
evecs.clear();
|
||||
|
||||
Eigen::ComplexEigenSolver<Eigen::MatrixXcd> es;
|
||||
es.compute(S);
|
||||
evals = es.eigenvalues();
|
||||
littleEvecs = es.eigenvectors();
|
||||
|
||||
// Convert evecs to lattice fields
|
||||
for (int k = 0; k < evals.size(); k++) {
|
||||
Eigen::VectorXcd vec = littleEvecs.col(k);
|
||||
Field tmp (basis[0].Grid());
|
||||
tmp = Zero();
|
||||
for (int j = 0; j < basis.size(); j++) {
|
||||
tmp = tmp + vec[j] * basis[j];
|
||||
}
|
||||
evecs.push_back(tmp);
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage << "Eigenvalues: " << std::endl << evals << std::endl;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the factorization DV = V^\dag H + f e^\dag with the last-computed
|
||||
* V, H, f.
|
||||
*/
|
||||
// RealD verifyFactorization() {
|
||||
// int k = basis.size(); // number of basis vectors, also the size of H.
|
||||
// std::vector<Field> factorized (k, Zero());
|
||||
// Field tmp (FGrid); tmp = Zero();
|
||||
// for (int i = 0; i < basis.size(); i++) {
|
||||
// Linop.Op(basis[i], tmp);
|
||||
// }
|
||||
// // basisRotate(basis, Q, 0, Nk, 0, Nk, Nm);
|
||||
// // Linop.Op(, )
|
||||
// }
|
||||
|
||||
/* Getters */
|
||||
Eigen::MatrixXcd getHessenbergMat() { return Hess; }
|
||||
Field getF() { return f; }
|
||||
std::vector<Field> getBasis() { return basis; }
|
||||
Eigen::VectorXcd getEvals() { return evals; }
|
||||
std::vector<Field> getEvecs() { return evecs; }
|
||||
|
||||
/**
|
||||
* Implements implicit restarting for Arnoldi. Assumes eigenvalues are sorted.
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* int _Nm
|
||||
* Size of basis to keep (Hessenberg is MxM).
|
||||
* int Nk
|
||||
* Number of basis vectors to keep at each restart.
|
||||
*/
|
||||
void implicitRestart(int _Nm, int _Nk) {
|
||||
assert ( _Nk <= _Nm );
|
||||
Nm = _Nm; Nk = _Nk;
|
||||
int Np = Nm - Nk; // keep Nk smallest (or largest, depends on sort function) evecs
|
||||
|
||||
std::cout << GridLogMessage << "Computing QR Factorizations." << std::endl;
|
||||
|
||||
Eigen::MatrixXcd Q = Eigen::MatrixXcd::Identity(Nm, Nm);
|
||||
Eigen::MatrixXcd Qi (Nm, Nm);
|
||||
Eigen::MatrixXcd R (Nm, Nm);
|
||||
|
||||
for (int i = Nk; i < Nm; i++) { // keep the first Nk eigenvalues and iterate through the last Np. Should loop Np times
|
||||
|
||||
// Useful debugging output
|
||||
std::cout << GridLogDebug << "Computing QR factorization for i = " << i << std::endl;
|
||||
std::cout << GridLogDebug << "Eval shift = " << evals[i] << std::endl;
|
||||
std::cout << GridLogDebug << "Hess before rotation: " << Hess << std::endl;
|
||||
|
||||
// QR factorize
|
||||
Eigen::HouseholderQR<Eigen::MatrixXcd> QR (Hess - evals[i] * Eigen::MatrixXcd::Identity(Nm, Nm));
|
||||
Qi = QR.householderQ();
|
||||
Q = Q * Qi;
|
||||
Hess = Qi.adjoint() * Hess * Qi;
|
||||
|
||||
std::cout << GridLogDebug << "Qt up to i = " << Q.transpose() << std::endl;
|
||||
|
||||
}
|
||||
|
||||
std::cout << GridLogDebug << "Hess after all rotations: " << std::endl << Hess << std::endl;
|
||||
|
||||
// form Arnoldi vector f: f is normal to the basis vectors and its norm \beta is used to determine the Ritz estimate.
|
||||
std::complex<double> beta = Hess(Nk, Nk-1);
|
||||
std::complex<double> sigma = Q(Nm-1, Nk-1);
|
||||
f = basis[Nk] * beta + f * sigma;
|
||||
RealD betak = std::sqrt(norm2(f));
|
||||
std::cout << GridLogMessage << "|f|^2 after implicit restart = " << norm2(f) << std::endl;
|
||||
|
||||
// Rotate basis by Qt
|
||||
Qt = Q.transpose();
|
||||
basisRotate(basis, Qt, 0, Nk + 1, 0, Nm, Nm);
|
||||
|
||||
// rotate
|
||||
basisRotate(evecs, Qt, 0, Nk + 1, 0, Nm, Nm);
|
||||
|
||||
// Truncate the basis and restart
|
||||
basis = std::vector<Field> (basis.begin(), basis.begin() + Nk);
|
||||
// evecs = std::vector<Field> (evecs.begin(), evecs.begin() + Nk);
|
||||
Hess = Hess(Eigen::seqN(0, Nk), Eigen::seqN(0, Nk));
|
||||
|
||||
std::cout << "evecs size: " << evecs.size() << std::endl;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the number of Arnoldi eigenvectors that have converged. An eigenvector s is considered converged
|
||||
* for a tolerance epsilon if
|
||||
* r(s) := |\beta e_m^T s| < epsilon
|
||||
* where beta is the norm of f_{m+1}.
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
*
|
||||
* Returns
|
||||
* -------
|
||||
* int : Number of converged eigenvectors.
|
||||
*/
|
||||
int converged() {
|
||||
int Nconv = 0;
|
||||
for (int k = 0; k < evecs.size(); k++) {
|
||||
RealD emTs = std::abs(littleEvecs(Nm - 1, k)); // e_m^T s
|
||||
RealD ritzEstimate = beta_k * emTs;
|
||||
// TODO should be ritzEstimate < Tolerance * lambda_max
|
||||
std::cout << GridLogMessage << "Ritz estimate for evec " << k << " = " << ritzEstimate << std::endl;
|
||||
if (ritzEstimate < rtol) {
|
||||
Nconv++;
|
||||
}
|
||||
}
|
||||
return Nconv;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
#endif
|
||||
@@ -0,0 +1,878 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/iterative/BlockKrylovSchur.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Peter Boyle <paboyle@ph.ed.ac.uk>
|
||||
Author: Chulwoo Jung <chulwoo@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_BLOCKED_KRYLOV_SCHUR_H
|
||||
#define GRID_BLOCKED_KRYLOV_SCHUR_H
|
||||
|
||||
#include <iomanip>
|
||||
#include <numeric>
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
/**
|
||||
* Block (block-Arnoldi) restarted Krylov-Schur eigensolver for
|
||||
* general non-Hermitian operators.
|
||||
*
|
||||
* Algorithm
|
||||
* ---------
|
||||
* Uses a block Arnoldi factorisation of block size Nblock:
|
||||
*
|
||||
* A V_k = V_k H_k + F_k B_k^dag
|
||||
*
|
||||
* where
|
||||
* V_k = Nm orthonormal basis vectors (stored flat in basis[])
|
||||
* H_k = Nm x Nm upper block-Hessenberg Rayleigh quotient
|
||||
* F_k = Nblock residual vectors (the next block beyond V_k)
|
||||
* B_k = Nm x Nblock coupling matrix (non-zero only in last Nblock rows)
|
||||
*
|
||||
* Each block Arnoldi step applies A to each of the Nblock vectors in the
|
||||
* current block, orthogonalises against all previous basis vectors, and
|
||||
* reduces the residual block to upper-triangular form via Householder QR
|
||||
* (implemented here as modified Gram-Schmidt within the block).
|
||||
*
|
||||
* The restart is a thick restart via the Schur decomposition of H_k:
|
||||
* H_k = Q^dag S Q
|
||||
* The leading Nk Schur vectors (chosen by RitzFilter) are retained,
|
||||
* the basis and Rayleigh quotient are truncated, and block Arnoldi continues
|
||||
* from the (Nk/Nblock)-th block.
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* Nblock : block size p
|
||||
* Nm : total Krylov dimension (must be divisible by Nblock)
|
||||
* Nk : total vectors to keep after each restart (must be divisible by Nblock, Nk < Nm)
|
||||
* Nstop : declare convergence when this many eigenpairs have converged
|
||||
* MaxIter : maximum number of outer (restart) iterations
|
||||
* Tolerance : relative convergence tolerance (||r|| < Tolerance * |lambda_max|)
|
||||
*/
|
||||
template<class Field>
|
||||
class BlockKrylovSchur {
|
||||
|
||||
protected:
|
||||
//--------------------------------------------------------------------
|
||||
// Types
|
||||
//--------------------------------------------------------------------
|
||||
typedef Eigen::MatrixXcd CMat;
|
||||
typedef Eigen::VectorXcd CVec;
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Parameters (set by operator())
|
||||
//--------------------------------------------------------------------
|
||||
int Nblock; // block size
|
||||
int Nm; // total Krylov dimension (multiple of Nblock)
|
||||
int Nk; // total vectors retained after restart (multiple of Nblock)
|
||||
int Nstop;
|
||||
int MaxIter;
|
||||
RealD Tolerance;
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Internal state
|
||||
//--------------------------------------------------------------------
|
||||
LinearOperatorBase<Field>& Linop;
|
||||
GridBase* Grid_;
|
||||
RitzFilter ritzFilter;
|
||||
|
||||
// Prefix used in log messages; derived classes override in their constructor
|
||||
// (e.g. "HarmonicBlockKrylovSchur") so the shared code reports the right name.
|
||||
std::string className = "BlockKrylovSchur";
|
||||
|
||||
// Flat storage: basis[s*Nblock + t] is the t-th vector of block s
|
||||
// After construction: basis has Nm entries
|
||||
std::vector<Field> basis;
|
||||
|
||||
// Rayleigh quotient Nm x Nm
|
||||
CMat H;
|
||||
|
||||
// Residual block: Nblock vectors (the (Nm/Nblock+1)-th block, unnormalised before
|
||||
// QR; normalised and orthogonalised as part of block Arnoldi)
|
||||
std::vector<Field> F;
|
||||
|
||||
// Coupling matrix B: Nm x Nblock.
|
||||
// In exact arithmetic only the last Nblock rows are non-zero:
|
||||
// B(Nm - Nblock + t, s) = H_{Nm/Nblock+1, Nm/Nblock}(t, s) (the subdiagonal block)
|
||||
// We keep it as a full matrix for generality after restarts.
|
||||
CMat B;
|
||||
|
||||
RealD beta_k; // Frobenius norm of the last subdiagonal block
|
||||
RealD rtol; // absolute tolerance = Tolerance * approxLambdaMax
|
||||
|
||||
// Output
|
||||
CVec evals;
|
||||
CMat littleEvecs; // Nm columns
|
||||
std::vector<RealD> ritzEstimates;
|
||||
|
||||
public:
|
||||
std::vector<Field> evecs;
|
||||
bool doEvalCheck = false;
|
||||
// When true (and Nblock even), only Nblock/2 starting vectors are required.
|
||||
// The remaining Nblock/2 slots are filled by pairing each supplied vector
|
||||
// with its parity-flipped partner (sign negated on odd checkerboard sites).
|
||||
bool useParityFlip = false;
|
||||
// Same pairing behaviour but the partner is produced by gamma5Func(v).
|
||||
// gamma5Func must be set by the caller before operator() is called.
|
||||
// It is a std::function so that BlockKrylovSchur.h does not need to know
|
||||
// about the Grid QCD Gamma class (which is defined at a later include layer).
|
||||
bool useGamma5 = false;
|
||||
std::function<void(const Field&, Field&)> gamma5Func;
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Constructor
|
||||
//--------------------------------------------------------------------
|
||||
BlockKrylovSchur(LinearOperatorBase<Field>& _Linop, GridBase* _Grid,
|
||||
RealD _Tolerance, RitzFilter _rf = EvalReSmall)
|
||||
: Linop(_Linop), Grid_(_Grid), Tolerance(_Tolerance), ritzFilter(_rf),
|
||||
Nblock(-1), Nm(-1), Nk(-1), Nstop(-1), MaxIter(-1),
|
||||
beta_k(0.0), rtol(0.0)
|
||||
{}
|
||||
|
||||
virtual ~BlockKrylovSchur() = default;
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Main entry point
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* Run the blocked Krylov-Schur algorithm.
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* v0 : block of Nblock starting vectors (size >= Nblock)
|
||||
* _maxIter : maximum outer (restart) iterations
|
||||
* _Nm : total Krylov dimension (must be divisible by _Nblock)
|
||||
* _Nk : total vectors to keep after restart (must be divisible by _Nblock, _Nk < _Nm)
|
||||
* _Nstop : stop after _Nstop eigenvalues converged
|
||||
* _Nblock : block size
|
||||
*/
|
||||
virtual void operator()(const std::vector<Field>& v0, int _maxIter, int _Nm, int _Nk,
|
||||
int _Nstop, int _Nblock = 1, bool doubleOrthog = true,
|
||||
bool doVerify = false)
|
||||
{
|
||||
MaxIter = _maxIter;
|
||||
Nm = _Nm;
|
||||
Nk = _Nk;
|
||||
Nstop = _Nstop;
|
||||
Nblock = _Nblock;
|
||||
|
||||
{
|
||||
int divisor = 1;
|
||||
if (useParityFlip) divisor *= 2;
|
||||
if (useGamma5) divisor *= 2;
|
||||
assert(Nblock % divisor == 0 && (int)v0.size() >= Nblock / divisor);
|
||||
std::cout << GridLogMessage << className << ": divisor = " << divisor << std::endl;
|
||||
}
|
||||
assert(Nm % Nblock == 0);
|
||||
assert(Nk % Nblock == 0);
|
||||
assert(Nk < Nm);
|
||||
if (useGamma5) assert(gamma5Func && "useGamma5: gamma5Func must be set");
|
||||
preRun(); // hook: derived classes add parameter assertions here
|
||||
|
||||
int N = Nm; // total Krylov dimension
|
||||
|
||||
// Approximate largest eigenvalue for tolerance normalisation
|
||||
RealD approxLambdaMax = approxMaxEval(v0[0]);
|
||||
rtol = Tolerance * approxLambdaMax;
|
||||
std::cout << GridLogMessage << className << ": approx max eval = "
|
||||
<< approxLambdaMax << ", rtol = " << rtol << std::endl;
|
||||
|
||||
// Initialise
|
||||
H = CMat::Zero(N, N);
|
||||
B = CMat::Zero(N, Nblock);
|
||||
|
||||
int start = 0;
|
||||
std::vector<Field> startBlock = expandStartBlock(v0);
|
||||
|
||||
for (int iter = 0; iter < MaxIter; iter++) {
|
||||
std::cout << GridLogMessage << className << ": restart iteration " << iter << std::endl;
|
||||
|
||||
// ---- Block Arnoldi: extend from block start to block Nm/Nblock ----
|
||||
blockArnoldiIteration(startBlock, Nm/Nblock, start, doubleOrthog);
|
||||
|
||||
// After first full cycle start from block Nk/Nblock
|
||||
start = Nk/Nblock;
|
||||
|
||||
if (doVerify) {
|
||||
std::string lbl = "iter " + std::to_string(iter) + " after Arnoldi";
|
||||
verify(lbl);
|
||||
}
|
||||
|
||||
// ---- Restart rotation: compute Q and the rotated+reordered Rayleigh
|
||||
// quotient Hnew. Base class uses the plain Schur decomposition of
|
||||
// H; derived classes (e.g. HarmonicBlockKrylovSchur) override this
|
||||
// to target a shift.
|
||||
CMat Q, Hnew;
|
||||
restartRotation(Q, Hnew);
|
||||
CMat Qt = Q.adjoint();
|
||||
|
||||
// Rotate Krylov basis: basis_new[i] = sum_j basis[j] * Qt(j,i)
|
||||
std::vector<Field> basis2;
|
||||
constructUR(basis2, basis, Qt, N);
|
||||
basis = basis2;
|
||||
|
||||
// Update B and H
|
||||
B = Q * B;
|
||||
H = Hnew;
|
||||
|
||||
// ---- Truncate to Nk ----
|
||||
int Nkeep = Nk;
|
||||
|
||||
CMat Htmp = H(Eigen::seqN(0, Nkeep), Eigen::seqN(0, Nkeep));
|
||||
H = CMat::Zero(N, N);
|
||||
H(Eigen::seqN(0, Nkeep), Eigen::seqN(0, Nkeep)) = Htmp;
|
||||
|
||||
std::vector<Field> basisTmp(basis.begin(), basis.begin() + Nkeep);
|
||||
basis = basisTmp;
|
||||
|
||||
CMat Btmp = B(Eigen::seqN(0, Nkeep), Eigen::all);
|
||||
B = CMat::Zero(N, Nblock);
|
||||
B(Eigen::seqN(0, Nkeep), Eigen::all) = Btmp;
|
||||
|
||||
// beta_k = Frobenius norm of the effective coupling
|
||||
beta_k = Btmp.norm();
|
||||
std::cout << GridLogMessage << className << ": beta_k = " << beta_k << std::endl;
|
||||
|
||||
// Restart: the new starting block is F (the residual block from Arnoldi)
|
||||
startBlock = F;
|
||||
|
||||
if (doVerify) {
|
||||
std::string lbl = "iter " + std::to_string(iter) + " after restart+truncation";
|
||||
verify(lbl);
|
||||
}
|
||||
|
||||
// ---- Compute eigensystem of truncated H for convergence check ----
|
||||
CMat Hk = H(Eigen::seqN(0, Nkeep), Eigen::seqN(0, Nkeep));
|
||||
computeEigensystem(Hk, Nkeep);
|
||||
|
||||
int Nconv = converged(Nkeep);
|
||||
std::cout << GridLogMessage << className << ": converged " << Nconv
|
||||
<< " / " << Nstop << std::endl;
|
||||
|
||||
if (Nconv >= Nstop || iter == MaxIter - 1) {
|
||||
std::cout << GridLogMessage << className << ": done after " << iter
|
||||
<< " restarts, " << Nconv << " converged." << std::endl;
|
||||
std::cout << GridLogMessage << "Eigenvalues: " << evals << std::endl;
|
||||
|
||||
if (doEvalCheck) {
|
||||
Field w(Grid_);
|
||||
for (int k = 0; k < (int)evecs.size(); k++) {
|
||||
Linop.Op(evecs[k], w);
|
||||
ComplexD eval_est = toStdCmplx(innerProduct(evecs[k], w));
|
||||
w -= eval_est * evecs[k];
|
||||
RealD res = std::sqrt(norm2(w));
|
||||
std::cout << GridLogMessage << className << ": evec[" << k << "]"
|
||||
<< " eval_reported = " << evals[k]
|
||||
<< " eval_est = " << eval_est
|
||||
<< " || A v - eval_est * v || = " << res << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Accessors
|
||||
std::vector<Field> getEvecs() { return evecs; }
|
||||
CVec getEvals() { return evals; }
|
||||
std::vector<RealD> getRitzEstimates() { return ritzEstimates; }
|
||||
|
||||
// Negate the field on all odd-parity (checkerboard) sites.
|
||||
// Uses pickCheckerboard/setCheckerboard so the SIMD layout is handled
|
||||
// correctly and the negation runs in parallel.
|
||||
static void parityFlippedField(const Field& v, Field& out) {
|
||||
GridCartesian* cgrid = dynamic_cast<GridCartesian*>(v.Grid());
|
||||
assert(cgrid != nullptr);
|
||||
GridRedBlackCartesian rbgrid(cgrid);
|
||||
Field veven(&rbgrid), vodd(&rbgrid);
|
||||
pickCheckerboard(Even, veven, v);
|
||||
pickCheckerboard(Odd, vodd, v);
|
||||
vodd = -vodd;
|
||||
setCheckerboard(out, veven);
|
||||
setCheckerboard(out, vodd);
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Verification: print H and B, check A V = V H + F B^dag explicitly
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* Checks the block Arnoldi / Krylov-Schur decomposition
|
||||
*
|
||||
* A V = V H + F B^dag (KS)
|
||||
*
|
||||
* by explicit operator applications. For each basis vector j:
|
||||
*
|
||||
* w_j = A basis[j]
|
||||
*
|
||||
* The nBasis × nBasis matrix M of inner products is computed:
|
||||
*
|
||||
* M[i, j] = <basis[i] | A basis[j]>
|
||||
*
|
||||
* and compared column-by-column against H. Separately, the nBasis × Nblock
|
||||
* residual coupling matrix R is computed:
|
||||
*
|
||||
* R[j, t] = <basis[j] | F[t]> * ||F[t]|| (scaled by F-block norms)
|
||||
*
|
||||
* but since F is already normalised, R[j,t] = <basis[j] | F[t]>.
|
||||
*
|
||||
* The KS relation for column j reads:
|
||||
* w_j = sum_i basis[i] H[i,j] + sum_t F[t] B[j,t]*
|
||||
* so the deviation in column j is
|
||||
* dev_j = w_j - sum_i basis[i] M[i,j] (should be zero for exact arithmetic)
|
||||
* augmented by the F B^dag term in the last block.
|
||||
*
|
||||
* Prints:
|
||||
* - H (current Rayleigh quotient, nBasis × nBasis)
|
||||
* - B (coupling matrix, nBasis × Nblock)
|
||||
* - M (explicit inner product matrix <V | A V>)
|
||||
* - max |H[i,j] - M[i,j]| (should be O(machine epsilon))
|
||||
* - for each basis column j: || A v_j - V H[:,j] - F B[j,:]^* ||
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* label : string printed at the start (e.g. "after restart 2")
|
||||
*/
|
||||
void verify(const std::string& label = "")
|
||||
{
|
||||
int nBasis = (int)basis.size();
|
||||
int nF = (int)F.size();
|
||||
|
||||
if (nBasis == 0) {
|
||||
std::cout << GridLogMessage
|
||||
<< className << "::verify [" << label
|
||||
<< "]: basis is empty." << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
// Full allocated dimension of H (= Nm); may be larger than nBasis after restart+truncation
|
||||
int Nfull = (int)H.rows();
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "======== " << className << "::verify [" << label << "] ========" << std::endl;
|
||||
std::cout << GridLogMessage
|
||||
<< " nBasis = " << nBasis << " Nfull = " << Nfull
|
||||
<< " Nblock = " << Nblock << " nF = " << nF << std::endl;
|
||||
|
||||
// ---- Print H (full Nm x Nm matrix) ----
|
||||
// After restart+truncation nBasis < Nfull; entries outside [0:nBasis,0:nBasis]
|
||||
// should be ~0 — printing the full matrix makes this visible.
|
||||
std::cout << GridLogMessage << "H (" << Nfull << " x " << Nfull << "):" << std::endl;
|
||||
for (int i = 0; i < Nfull; i++) {
|
||||
for (int j = 0; j < Nfull; j++)
|
||||
std::cout << " " << std::setprecision(4) << std::setw(14) << H(i, j);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
// ---- Print B (full Nm x Nblock matrix) ----
|
||||
std::cout << GridLogMessage << "B (" << Nfull << " x " << nF << "):" << std::endl;
|
||||
for (int i = 0; i < Nfull; i++) {
|
||||
for (int t = 0; t < nF; t++)
|
||||
std::cout << " " << std::setprecision(4) << std::setw(14) << B(i, t);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
// ---- Compute M[i,j] = <basis[i] | A basis[j]> ----
|
||||
CMat M = CMat::Zero(nBasis, nBasis);
|
||||
Field w(Grid_);
|
||||
for (int j = 0; j < nBasis; j++) {
|
||||
Linop.Op(basis[j], w);
|
||||
for (int i = 0; i < nBasis; i++)
|
||||
M(i, j) = toStdCmplx(innerProduct(basis[i], w));
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage << "M = <V|AV> (" << nBasis << " x " << nBasis << "):" << std::endl;
|
||||
for (int i = 0; i < nBasis; i++) {
|
||||
for (int j = 0; j < nBasis; j++)
|
||||
std::cout << " " << std::setprecision(4) << std::setw(14) << M(i, j);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
// ---- max |H - M| (for the nBasis x nBasis Rayleigh-quotient block) ----
|
||||
RealD maxHM = 0.0;
|
||||
for (int i = 0; i < nBasis; i++)
|
||||
for (int j = 0; j < nBasis; j++)
|
||||
maxHM = std::max(maxHM, std::abs(H(i,j) - M(i,j)));
|
||||
std::cout << GridLogMessage
|
||||
<< " max |H[i,j] - M[i,j]| (i,j < nBasis) = " << maxHM << std::endl;
|
||||
|
||||
// ---- Check entries of H OUTSIDE the nBasis x nBasis block ----
|
||||
// These live in rows i >= nBasis or columns j >= nBasis.
|
||||
// They must be ~0 after restart+truncation (before the coupling rows are
|
||||
// re-filled by the next blockArnoldiIteration call).
|
||||
// During a full Arnoldi run (nBasis == Nfull) this loop is a no-op.
|
||||
RealD maxOutside = 0.0;
|
||||
for (int i = 0; i < Nfull; i++)
|
||||
for (int j = 0; j < Nfull; j++)
|
||||
if (i >= nBasis || j >= nBasis)
|
||||
maxOutside = std::max(maxOutside, std::abs(H(i,j)));
|
||||
if (Nfull > nBasis)
|
||||
std::cout << GridLogMessage
|
||||
<< " max |H[i,j]| outside [0:" << nBasis << ",0:" << nBasis
|
||||
<< "] block = " << maxOutside
|
||||
<< " (should be ~0 after restart+truncation)" << std::endl;
|
||||
|
||||
// ---- Check orthonormality of basis ----
|
||||
CMat G = CMat::Zero(nBasis, nBasis);
|
||||
for (int i = 0; i < nBasis; i++)
|
||||
for (int j = 0; j < nBasis; j++)
|
||||
G(i, j) = toStdCmplx(innerProduct(basis[i], basis[j]));
|
||||
CMat Gerr = G - CMat::Identity(nBasis, nBasis);
|
||||
std::cout << GridLogMessage
|
||||
<< " max |<V_i|V_j> - delta_ij| = " << Gerr.cwiseAbs().maxCoeff() << std::endl;
|
||||
|
||||
// ---- Per-column residual: || A v_j - V H[:,j] - F B[j,:]^* || ----
|
||||
// For each basis vector j, compute A v_j then subtract V H[:,j] and F B[j,:]^*
|
||||
RealD maxColDev = 0.0;
|
||||
for (int j = 0; j < nBasis; j++) {
|
||||
Linop.Op(basis[j], w);
|
||||
|
||||
// subtract V H[:,j]
|
||||
for (int i = 0; i < nBasis; i++)
|
||||
w -= basis[i] * H(i, j);
|
||||
|
||||
// subtract F B[j,:]^* (F[t] * conj(B[j,t]))
|
||||
for (int t = 0; t < nF; t++)
|
||||
w -= F[t] * std::conj(B(j, t));
|
||||
|
||||
RealD dev = std::sqrt(norm2(w));
|
||||
std::cout << GridLogMessage
|
||||
<< " || A v[" << j << "] - V H[:,j] - F B[j,:]* || = " << dev << std::endl;
|
||||
maxColDev = std::max(maxColDev, dev);
|
||||
}
|
||||
std::cout << GridLogMessage
|
||||
<< " max column deviation = " << maxColDev << std::endl;
|
||||
|
||||
// ---- Check F block orthogonality against basis ----
|
||||
if (nF > 0) {
|
||||
RealD maxFV = 0.0;
|
||||
for (int t = 0; t < nF; t++)
|
||||
for (int i = 0; i < nBasis; i++) {
|
||||
RealD ip = std::abs(toStdCmplx(innerProduct(basis[i], F[t])));
|
||||
maxFV = std::max(maxFV, ip);
|
||||
}
|
||||
std::cout << GridLogMessage
|
||||
<< " max |<V_i | F_t>| (should be ~0) = " << maxFV << std::endl;
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "======== end verify ========" << std::endl;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Extension hooks for derived classes
|
||||
//--------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Apply the operator (or poly-filtered operator) to the current Arnoldi
|
||||
* block and return the results in W.
|
||||
*
|
||||
* Base implementation: W[t] = Linop.Op(basis[kBase + t]).
|
||||
* Derived classes (e.g. SplitGridBlockKrylovSchur) override this to
|
||||
* apply poly(A) via Grid_split / Grid_unsplit instead.
|
||||
*/
|
||||
virtual void applyBlock(std::vector<Field>& W, int kBase)
|
||||
{
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
Linop.Op(basis[kBase + t], W[t]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called once at the start of operator(), after parameters are set.
|
||||
* Base implementation is a no-op; derived classes override to add
|
||||
* parameter assertions (e.g. Nblock % mrhs == 0).
|
||||
*/
|
||||
virtual void preRun() {}
|
||||
|
||||
/**
|
||||
* Compute the restart rotation for the current Rayleigh quotient H.
|
||||
*
|
||||
* Returns Q (unitary) and Hnew = Q H Q^dag reordered so that the wanted
|
||||
* Nk eigenvalues occupy the leading block, ready for truncation.
|
||||
*
|
||||
* Base implementation: the plain Schur decomposition of H, reordered by
|
||||
* ritzFilter. HarmonicBlockKrylovSchur overrides this to Schur-decompose
|
||||
* the shifted quotient (H - sigma I) so that eigenvalues nearest sigma are
|
||||
* selected.
|
||||
*/
|
||||
virtual void restartRotation(CMat& Q, CMat& Hnew)
|
||||
{
|
||||
ComplexSchurDecomposition schur(H, false, ritzFilter);
|
||||
std::cout << GridLogMessage << className << ": Schur decomposed." << std::endl;
|
||||
schur.schurReorder(Nk);
|
||||
std::cout << GridLogMessage << className << ": Schur reordered." << std::endl;
|
||||
Q = schur.getMatrixQ();
|
||||
Hnew = schur.getMatrixS();
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Starting-block expansion (parity flip / gamma5 partners)
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* Expand Nblock/divisor seed vectors into the full Nblock starting block by
|
||||
* pairing each seed with its parity-flipped and/or gamma5 partners. Order:
|
||||
* {v, flip(v)} then doubled by {., g5(.)} giving {v, flip(v), g5(v),
|
||||
* g5(flip(v))} when both flags are set. Requires Nblock, Grid_ and the
|
||||
* flags to be set.
|
||||
*/
|
||||
std::vector<Field> expandStartBlock(const std::vector<Field>& v0)
|
||||
{
|
||||
int divisor = (useParityFlip ? 2 : 1) * (useGamma5 ? 2 : 1);
|
||||
std::vector<Field> startBlock;
|
||||
startBlock.reserve(Nblock);
|
||||
for (int i = 0; i < Nblock / divisor; i++) {
|
||||
std::vector<Field> group;
|
||||
group.push_back(v0[i]);
|
||||
if (useParityFlip) {
|
||||
int n = (int)group.size();
|
||||
for (int j = 0; j < n; j++) {
|
||||
Field fp(Grid_);
|
||||
parityFlippedField(group[j], fp);
|
||||
group.push_back(std::move(fp));
|
||||
}
|
||||
}
|
||||
if (useGamma5) {
|
||||
int n = (int)group.size();
|
||||
for (int j = 0; j < n; j++) {
|
||||
Field g5v(Grid_);
|
||||
gamma5Func(group[j], g5v);
|
||||
group.push_back(std::move(g5v));
|
||||
}
|
||||
}
|
||||
for (auto& f : group) startBlock.push_back(std::move(f));
|
||||
}
|
||||
return startBlock;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Block Arnoldi iteration
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* Extends the block Arnoldi factorisation from block index 'start' to
|
||||
* block index 'Nm'.
|
||||
*
|
||||
* On entry (start > 0): basis[0..start*Nblock-1] already set,
|
||||
* H[0..start*Nblock-1, 0..start*Nblock-1] already set,
|
||||
* B[start*Nblock-1, :] set (coupling from prior residual block).
|
||||
* startBlock = the normalised residual block F from the previous cycle.
|
||||
*
|
||||
* On entry (start == 0): initialises everything from startBlock.
|
||||
*/
|
||||
void blockArnoldiIteration(std::vector<Field>& startBlock, int endBlock,
|
||||
int startIdx, bool doubleOrthog)
|
||||
{
|
||||
int N = Nm;
|
||||
|
||||
if (startIdx == 0) {
|
||||
basis.clear();
|
||||
F.clear();
|
||||
H = CMat::Zero(N, N);
|
||||
B = CMat::Zero(N, Nblock);
|
||||
|
||||
// Orthonormalise starting block via modified Gram-Schmidt
|
||||
std::vector<Field> V0 = startBlock;
|
||||
blockOrthonormalise(V0);
|
||||
for (auto& v : V0) basis.push_back(v);
|
||||
} else {
|
||||
// Append residual block (startBlock = F_old) to basis.
|
||||
// The truncated KS relation after restart is:
|
||||
//
|
||||
// A V_k = V_k S_k + F_old B_old^dag (*)
|
||||
//
|
||||
// where V_k = basis[0:Nkeep], S_k is stored in H[0:Nkeep,0:Nkeep],
|
||||
// B_old = B[0:Nkeep,:], F_old = startBlock.
|
||||
//
|
||||
// Once F_old is appended as basis[Nkeep:Nkeep+Nblock], (*) becomes
|
||||
// a statement about the extended H matrix:
|
||||
//
|
||||
// H[Nkeep+t, j] = (B_old^dag)[t,j] = conj(B_old[j,t])
|
||||
// for t=0..Nblock-1, j=0..Nkeep-1
|
||||
//
|
||||
// These entries are the "restart coupling rows" that connect the new
|
||||
// block to all retained Schur vectors and must be set before Arnoldi
|
||||
// continues, otherwise A V_k = V_k H[:,0:Nkeep] would be missing the
|
||||
// F_old B_old^dag term for those columns.
|
||||
|
||||
int Nkeep = startIdx * Nblock;
|
||||
for (auto& v : startBlock) basis.push_back(v);
|
||||
|
||||
// Fill restart coupling rows into H
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
for (int j = 0; j < Nkeep; j++)
|
||||
H(Nkeep + t, j) = std::conj(B(j, t));
|
||||
|
||||
// Zero out B for the retained columns now that the coupling is in H
|
||||
for (int j = 0; j < Nkeep; j++)
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
B(j, t) = 0.0;
|
||||
}
|
||||
|
||||
// Main block Arnoldi loop
|
||||
for (int k = startIdx; k < endBlock; k++) {
|
||||
blockArnoldiStep(k, doubleOrthog);
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* One block Arnoldi step: extends by one block (Nblock vectors).
|
||||
*
|
||||
* Computes block column k of H and the next basis block V_{k+1}.
|
||||
*
|
||||
* Layout of basis (flat):
|
||||
* basis[j*Nblock + t] = t-th vector of j-th block, j = 0..k
|
||||
*
|
||||
* After this call:
|
||||
* H[i, k*Nblock : (k+1)*Nblock] filled for i = 0..(k+1)*Nblock - 1
|
||||
* basis[k*Nblock .. (k+1)*Nblock - 1] normalised (already set on entry)
|
||||
* F = residual block (to become V_{k+1} after this step if k < Nm-1)
|
||||
*
|
||||
* If k < Nm-1, also:
|
||||
* H[(k+1)*Nblock : (k+2)*Nblock, k*Nblock : (k+1)*Nblock] = subdiag block (from QR of residual)
|
||||
* basis extended by Nblock (the normalised residual vectors)
|
||||
*/
|
||||
void blockArnoldiStep(int k, bool doubleOrthog)
|
||||
{
|
||||
int kBase = k * Nblock; // first flat index of current block
|
||||
int prevN = kBase + Nblock; // number of basis vectors so far after this step
|
||||
int N = Nm;
|
||||
|
||||
// W[t] = op(basis[kBase + t]) — dispatches to applyBlock() virtual
|
||||
std::vector<Field> W(Nblock, Field(Grid_));
|
||||
applyBlock(W, kBase);
|
||||
|
||||
// Orthogonalise W against all current basis vectors (full reorthogonalisation)
|
||||
// H[i, kBase + t] = <basis[i] | W[t]>
|
||||
for (int pass = 0; pass < (doubleOrthog ? 2 : 1); pass++) {
|
||||
for (int i = 0; i < prevN; i++) {
|
||||
for (int t = 0; t < Nblock; t++) {
|
||||
ComplexD coeff = innerProduct(basis[i], W[t]);
|
||||
if (pass == 0)
|
||||
H(i, kBase + t) = toStdCmplx(coeff);
|
||||
else
|
||||
H(i, kBase + t) += toStdCmplx(coeff);
|
||||
W[t] -= coeff * basis[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Store residual block F
|
||||
F = W;
|
||||
|
||||
if (k == Nm/Nblock - 1) {
|
||||
// Last block: compute coupling matrix B for KS decomp.
|
||||
//
|
||||
// blockQR modifies F in-place (F → Q orthonormal) and returns R
|
||||
// such that W_orig[t] = sum_s F[s] * R[s,t] (W_orig = F_after * R).
|
||||
//
|
||||
// The KS relation for column j = kBase+t requires the coefficient of F[s]
|
||||
// to be (B†)[s,j] = conj(B[j,s]). Matching with R[s,t]:
|
||||
// conj(B[kBase+t, s]) = R[s,t] → B[kBase+t, s] = conj(R[s,t])
|
||||
//
|
||||
// Equivalently the last Nblock rows of B are R^H (Hermitian conjugate of R).
|
||||
// Note: for Nblock=1, R is scalar real positive, so this reduces to B = R. ✓
|
||||
CMat R = blockQR(F); // F is modified in-place to become Q; returns R
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
for (int s = 0; s < Nblock; s++)
|
||||
B(kBase + t, s) = std::conj(R(s, t)); // B_block = R^H
|
||||
|
||||
beta_k = R.norm();
|
||||
return;
|
||||
}
|
||||
|
||||
// Not last block: QR-decompose residual to get V_{k+1}
|
||||
CMat R = blockQR(F); // F orthonormalised in-place, R is upper triangular
|
||||
|
||||
// Subdiagonal block of H: H[(k+1)*Nblock : (k+2)*Nblock, kBase : kBase+Nblock] = R
|
||||
int nextBase = (k + 1) * Nblock;
|
||||
for (int i = 0; i < Nblock; i++)
|
||||
for (int j = 0; j < Nblock; j++)
|
||||
H(nextBase + i, kBase + j) = R(i, j);
|
||||
|
||||
// Append normalised residual block to basis
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
basis.push_back(F[t]);
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Block QR via modified Gram-Schmidt within the block
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* Given a block of Nblock vectors W (not necessarily orthonormal),
|
||||
* orthonormalises them in-place and returns the upper-triangular R
|
||||
* such that W_in = W_out * R.
|
||||
*
|
||||
* Handles (near-)linear dependence by zeroing vectors below threshold.
|
||||
*/
|
||||
CMat blockQR(std::vector<Field>& W)
|
||||
{
|
||||
CMat R = CMat::Zero(Nblock, Nblock);
|
||||
const RealD deflThresh = 1e-14;
|
||||
|
||||
for (int j = 0; j < Nblock; j++) {
|
||||
// Orthogonalise W[j] against W[0..j-1]
|
||||
for (int i = 0; i < j; i++) {
|
||||
ComplexD coeff = innerProduct(W[i], W[j]);
|
||||
R(i, j) = toStdCmplx(coeff);
|
||||
W[j] -= coeff * W[i];
|
||||
}
|
||||
RealD nrm = std::sqrt(norm2(W[j]));
|
||||
R(j, j) = nrm;
|
||||
if (nrm > deflThresh) {
|
||||
W[j] *= (1.0 / nrm);
|
||||
} else {
|
||||
// deflation: zero this vector
|
||||
W[j] = Zero();
|
||||
std::cout << GridLogMessage
|
||||
<< className << ": deflation at block column " << j
|
||||
<< " (norm = " << nrm << ")" << std::endl;
|
||||
}
|
||||
}
|
||||
return R;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Orthonormalise a block against itself (no prior basis)
|
||||
//--------------------------------------------------------------------
|
||||
void blockOrthonormalise(std::vector<Field>& V)
|
||||
{
|
||||
for (int j = 0; j < (int)V.size(); j++) {
|
||||
for (int i = 0; i < j; i++) {
|
||||
ComplexD c = innerProduct(V[i], V[j]);
|
||||
V[j] -= c * V[i];
|
||||
}
|
||||
RealD nrm = std::sqrt(norm2(V[j]));
|
||||
assert(nrm > 1e-14);
|
||||
V[j] *= (1.0 / nrm);
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Basis rotation: UR[i] = sum_j U[j] * R(j, i)
|
||||
//--------------------------------------------------------------------
|
||||
void constructUR(std::vector<Field>& UR, std::vector<Field>& U,
|
||||
CMat& R, int N)
|
||||
{
|
||||
UR.clear();
|
||||
Field tmp(Grid_);
|
||||
for (int i = 0; i < N; i++) {
|
||||
tmp = Zero();
|
||||
for (int j = 0; j < N; j++)
|
||||
tmp += U[j] * R(j, i);
|
||||
UR.push_back(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Eigensystem of the truncated Rayleigh quotient
|
||||
//--------------------------------------------------------------------
|
||||
void computeEigensystem(CMat& Hk, int Nkeep)
|
||||
{
|
||||
Eigen::ComplexEigenSolver<CMat> es;
|
||||
es.compute(Hk);
|
||||
|
||||
// Sort to match schurReorder ordering.
|
||||
int n = es.eigenvalues().size();
|
||||
ComplexComparator cComp(ritzFilter);
|
||||
std::vector<int> idx(n);
|
||||
std::iota(idx.begin(), idx.end(), 0);
|
||||
std::sort(idx.begin(), idx.end(), [&](int a, int b){
|
||||
return cComp(toStdCmplx(es.eigenvalues()(a)), toStdCmplx(es.eigenvalues()(b)));
|
||||
});
|
||||
|
||||
evals.resize(n);
|
||||
littleEvecs.resize(n, n);
|
||||
for (int k = 0; k < n; k++) {
|
||||
evals(k) = es.eigenvalues()(idx[k]);
|
||||
littleEvecs.col(k) = es.eigenvectors().col(idx[k]);
|
||||
}
|
||||
|
||||
evecs.clear();
|
||||
for (int k = 0; k < Nkeep; k++) {
|
||||
CVec vec = littleEvecs.col(k);
|
||||
Field tmp(Grid_);
|
||||
tmp = Zero();
|
||||
for (int j = 0; j < (int)basis.size() && j < Nkeep; j++)
|
||||
tmp += vec[j] * basis[j];
|
||||
evecs.push_back(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Convergence check
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* An eigenpair (lambda, y) is converged if the Ritz estimate
|
||||
* r = || B^dag y ||
|
||||
* satisfies r < rtol. Here B is the (Nkeep x Nblock) coupling matrix
|
||||
* and y is the little eigenvector (Nkeep-vector) of H.
|
||||
*/
|
||||
int converged(int Nkeep)
|
||||
{
|
||||
ritzEstimates.clear();
|
||||
int Nconv = 0;
|
||||
|
||||
CMat Bk = B(Eigen::seqN(0, Nkeep), Eigen::all); // Nkeep x Nblock
|
||||
|
||||
for (int k = 0; k < Nkeep; k++) {
|
||||
CVec yk = littleEvecs.col(k); // Nkeep-vector
|
||||
CVec Bty = Bk.adjoint() * yk; // Nblock-vector
|
||||
RealD res = Bty.norm();
|
||||
ritzEstimates.push_back(res);
|
||||
std::cout << GridLogMessage << className << ": Ritz estimate[" << k
|
||||
<< "] = " << res << " eval = " << evals[k] << std::endl;
|
||||
if (res < rtol) Nconv++;
|
||||
else break;
|
||||
}
|
||||
return Nconv;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Approximate maximum eigenvalue via power iteration
|
||||
//--------------------------------------------------------------------
|
||||
RealD approxMaxEval(const Field& v0, int MAX_ITER = 50)
|
||||
{
|
||||
assert(norm2(v0) > 1e-8);
|
||||
RealD lam = 0.0, denom = std::sqrt(norm2(v0));
|
||||
Field vcur(Grid_), vtmp(Grid_);
|
||||
vcur = v0;
|
||||
for (int i = 0; i < MAX_ITER; i++) {
|
||||
Linop.Op(vcur, vtmp);
|
||||
vcur = vtmp;
|
||||
RealD num = std::sqrt(norm2(vcur));
|
||||
lam = num / denom;
|
||||
denom = num;
|
||||
}
|
||||
return lam;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
|
||||
#endif // GRID_BLOCKED_KRYLOV_SCHUR_H
|
||||
@@ -212,17 +212,13 @@ public:
|
||||
<< "\tTarget " << Tolerance << std::endl;
|
||||
|
||||
// std::cout << GridLogMessage << "\tPreamble " << PreambleTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tPreamble " << PreambleTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tConstruct " << ConstructTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tNorm " << NormTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tAssign " << AssignTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tSolver " << SolverTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "Solver breakdown "<<std::endl;
|
||||
std::cout << GridLogMessage << "\tMatrix " << MatrixTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tLinalg " << LinalgTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\t\tInner " << InnerTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\t\tAxpyNorm " << AxpyNormTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\t\tLinearComb " << LinearCombTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tSolver Elapsed " << SolverTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "Time breakdown "<<std::endl;
|
||||
std::cout << GridLogPerformance << "\tMatrix " << MatrixTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\tLinalg " << LinalgTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tInner " << InnerTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tAxpyNorm " << AxpyNormTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tLinearComb " << LinearCombTimer.Elapsed() <<std::endl;
|
||||
|
||||
std::cout << GridLogDebug << "\tMobius flop rate " << DwfFlops/ usecs<< " Gflops " <<std::endl;
|
||||
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/iterative/ConjugateGradientTimeslice.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Azusa Yamaguchi <ayamaguc@staffmail.ed.ac.uk>
|
||||
Author: Peter Boyle <paboyle@ph.ed.ac.uk>
|
||||
Author: paboyle <paboyle@ph.ed.ac.uk>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution
|
||||
directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_CONJUGATE_GRADIENT_TIMESLICE_H
|
||||
#define GRID_CONJUGATE_GRADIENT_TIMESLICE_H
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// Base classes for iterative processes based on operators
|
||||
// single input vec, single output vec.
|
||||
/////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Simple modification of conjugate gradient that outputs the residual as a function
|
||||
* of time, in order to study the large wavelength behavior of the solver.
|
||||
*/
|
||||
|
||||
|
||||
template <class Field>
|
||||
class ConjugateGradientTimeslice : public OperatorFunction<Field> {
|
||||
public:
|
||||
|
||||
using OperatorFunction<Field>::operator();
|
||||
|
||||
bool ErrorOnNoConverge; // throw an assert when the CG fails to converge.
|
||||
// Defaults true.
|
||||
RealD Tolerance;
|
||||
Integer MaxIterations;
|
||||
Integer IterationsToComplete; //Number of iterations the CG took to finish. Filled in upon completion
|
||||
RealD TrueResidual;
|
||||
|
||||
ConjugateGradientTimeslice(RealD tol, Integer maxit, bool err_on_no_conv = true)
|
||||
: Tolerance(tol),
|
||||
MaxIterations(maxit),
|
||||
ErrorOnNoConverge(err_on_no_conv)
|
||||
{};
|
||||
|
||||
virtual void LogIteration(int k,RealD a,RealD b){
|
||||
// std::cout << "ConjugageGradient::LogIteration() "<<std::endl;
|
||||
};
|
||||
virtual void LogBegin(void){
|
||||
std::cout << "ConjugageGradient::LogBegin() "<<std::endl;
|
||||
};
|
||||
|
||||
void operator()(LinearOperatorBase<Field> &Linop, const Field &src, Field &psi) {
|
||||
|
||||
this->LogBegin();
|
||||
|
||||
GRID_TRACE("ConjugateGradientTimeslice");
|
||||
GridStopWatch PreambleTimer;
|
||||
GridStopWatch ConstructTimer;
|
||||
GridStopWatch NormTimer;
|
||||
GridStopWatch AssignTimer;
|
||||
PreambleTimer.Start();
|
||||
psi.Checkerboard() = src.Checkerboard();
|
||||
|
||||
conformable(psi, src);
|
||||
|
||||
RealD cp, c, a, d, b, ssq, qq;
|
||||
//RealD b_pred;
|
||||
|
||||
// Was doing copies
|
||||
ConstructTimer.Start();
|
||||
Field p (src.Grid());
|
||||
Field mmp(src.Grid());
|
||||
Field r (src.Grid());
|
||||
ConstructTimer.Stop();
|
||||
|
||||
// Initial residual computation & set up
|
||||
NormTimer.Start();
|
||||
ssq = norm2(src); // Norm of source vector ||b||^2
|
||||
|
||||
ssqtx = localNorm2(src); // Norm |b(x, t)|^2 as a field
|
||||
std::vector<RealD> ssqt; // Norm of source not summed over time slices, ssq(t) = \sum_x |b(x, t)|^2
|
||||
sliceSum(ssqtx, ssqt, Tdir); // TODO make sure Tdir is globally defined
|
||||
|
||||
RealD guess = norm2(psi); // Norm of initial guess ||psi||^2
|
||||
NormTimer.Stop();
|
||||
assert(std::isnan(guess) == 0);
|
||||
AssignTimer.Start();
|
||||
if ( guess == 0.0 ) {
|
||||
r = src;
|
||||
p = r;
|
||||
a = ssq;
|
||||
} else {
|
||||
Linop.HermOpAndNorm(psi, mmp, d, b); //
|
||||
r = src - mmp; // Initial residual r0 = b - A guess
|
||||
p = r; // initial conj vector p0 = r0
|
||||
a = norm2(p);
|
||||
}
|
||||
cp = a;
|
||||
AssignTimer.Stop();
|
||||
|
||||
// Handle trivial case of zero src
|
||||
if (ssq == 0.){
|
||||
psi = Zero();
|
||||
IterationsToComplete = 1;
|
||||
TrueResidual = 0.;
|
||||
return;
|
||||
}
|
||||
|
||||
std::cout << GridLogIterative << std::setprecision(8) << "ConjugateGradient: guess " << guess << std::endl;
|
||||
std::cout << GridLogIterative << std::setprecision(8) << "ConjugateGradient: src " << ssq << std::endl;
|
||||
std::cout << GridLogIterative << std::setprecision(8) << "ConjugateGradient: mp " << d << std::endl;
|
||||
std::cout << GridLogIterative << std::setprecision(8) << "ConjugateGradient: mmp " << b << std::endl;
|
||||
std::cout << GridLogIterative << std::setprecision(8) << "ConjugateGradient: cp,r " << cp << std::endl;
|
||||
std::cout << GridLogIterative << std::setprecision(8) << "ConjugateGradient: p " << a << std::endl;
|
||||
|
||||
RealD rsq = Tolerance * Tolerance * ssq;
|
||||
|
||||
// Check if guess is really REALLY good :)
|
||||
if (cp <= rsq) {
|
||||
TrueResidual = std::sqrt(a/ssq);
|
||||
std::cout << GridLogMessage << "ConjugateGradient guess is converged already " << std::endl;
|
||||
IterationsToComplete = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
std::cout << GridLogIterative << std::setprecision(8)
|
||||
<< "ConjugateGradient: k=0 residual " << cp << " target " << rsq << std::endl;
|
||||
|
||||
PreambleTimer.Stop();
|
||||
GridStopWatch LinalgTimer;
|
||||
GridStopWatch InnerTimer;
|
||||
GridStopWatch AxpyNormTimer;
|
||||
GridStopWatch LinearCombTimer;
|
||||
GridStopWatch MatrixTimer;
|
||||
GridStopWatch SolverTimer;
|
||||
|
||||
RealD usecs = -usecond();
|
||||
SolverTimer.Start();
|
||||
int k;
|
||||
for (k = 1; k <= MaxIterations; k++) {
|
||||
|
||||
GridStopWatch IterationTimer;
|
||||
IterationTimer.Start();
|
||||
c = cp;
|
||||
|
||||
MatrixTimer.Start();
|
||||
Linop.HermOp(p, mmp); // Computes mmp = Ap
|
||||
MatrixTimer.Stop();
|
||||
|
||||
LinalgTimer.Start();
|
||||
|
||||
InnerTimer.Start();
|
||||
ComplexD dc = innerProduct(p,mmp); // p^\dagger A p
|
||||
InnerTimer.Stop();
|
||||
d = dc.real();
|
||||
a = c / d;
|
||||
|
||||
// What is axpy? Some accelerator or something? Check Lattice_arith.h
|
||||
AxpyNormTimer.Start();
|
||||
|
||||
// axpy_norm computes ax+by for vectors x and y compatible with a GPU. Here b is set to 1 (see the function in Lattice_reduction.h).
|
||||
// The first argument passes r by reference, so it stores r --> -a * Ap + 1 * r, i.e. it performs an update on
|
||||
// r_k --> r_{k+1} = r_k - \alpha_k A p_k. The function returns the norm squared of the first variable, i.e. ||r_{k+1}||^2.
|
||||
cp = axpy_norm(r, -a, mmp, r);
|
||||
AxpyNormTimer.Stop();
|
||||
b = cp / c;
|
||||
|
||||
LinearCombTimer.Start();
|
||||
{
|
||||
autoView( psi_v , psi, AcceleratorWrite);
|
||||
autoView( p_v , p, AcceleratorWrite);
|
||||
autoView( r_v , r, AcceleratorWrite);
|
||||
accelerator_for(ss,p_v.size(), Field::vector_object::Nsimd(),{
|
||||
coalescedWrite(psi_v[ss], a * p_v(ss) + psi_v(ss));
|
||||
coalescedWrite(p_v[ss] , b * p_v(ss) + r_v (ss));
|
||||
});
|
||||
}
|
||||
LinearCombTimer.Stop();
|
||||
LinalgTimer.Stop();
|
||||
LogIteration(k,a,b);
|
||||
|
||||
IterationTimer.Stop();
|
||||
if ( (k % 500) == 0 ) {
|
||||
std::cout << GridLogMessage << "ConjugateGradient: Iteration " << k
|
||||
<< " residual " << sqrt(cp/ssq) << " target " << Tolerance << std::endl;
|
||||
} else {
|
||||
std::cout << GridLogIterative << "ConjugateGradient: Iteration " << k
|
||||
<< " residual " << sqrt(cp/ssq) << " target " << Tolerance << " took " << IterationTimer.Elapsed() << std::endl;
|
||||
}
|
||||
|
||||
// Stopping condition
|
||||
if (cp <= rsq) {
|
||||
usecs +=usecond();
|
||||
SolverTimer.Stop();
|
||||
Linop.HermOpAndNorm(psi, mmp, d, qq);
|
||||
p = mmp - src;
|
||||
GridBase *grid = src.Grid();
|
||||
RealD DwfFlops = (1452. )*grid->gSites()*4*k
|
||||
+ (8+4+8+4+4)*12*grid->gSites()*k; // CG linear algebra
|
||||
RealD srcnorm = std::sqrt(norm2(src));
|
||||
RealD resnorm = std::sqrt(norm2(p));
|
||||
RealD true_residual = resnorm / srcnorm;
|
||||
std::cout << GridLogMessage << "ConjugateGradient Converged on iteration " << k
|
||||
<< "\tComputed residual " << std::sqrt(cp / ssq)
|
||||
<< "\tTrue residual " << true_residual
|
||||
<< "\tTarget " << Tolerance << std::endl;
|
||||
|
||||
// GridLogMessage logs the message to the terminal output; GridLogPerformance probably writes to a log file?
|
||||
// std::cout << GridLogMessage << "\tPreamble " << PreambleTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tSolver Elapsed " << SolverTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "Time breakdown "<<std::endl;
|
||||
std::cout << GridLogPerformance << "\tMatrix " << MatrixTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\tLinalg " << LinalgTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tInner " << InnerTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tAxpyNorm " << AxpyNormTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tLinearComb " << LinearCombTimer.Elapsed() <<std::endl;
|
||||
|
||||
std::cout << GridLogDebug << "\tMobius flop rate " << DwfFlops/ usecs<< " Gflops " <<std::endl;
|
||||
|
||||
if (ErrorOnNoConverge) assert(true_residual / Tolerance < 10000.0);
|
||||
|
||||
IterationsToComplete = k;
|
||||
TrueResidual = true_residual;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Failed. Calculate true residual before giving up
|
||||
// Linop.HermOpAndNorm(psi, mmp, d, qq);
|
||||
// p = mmp - src;
|
||||
//TrueResidual = sqrt(norm2(p)/ssq);
|
||||
// TrueResidual = 1;
|
||||
|
||||
std::cout << GridLogMessage << "ConjugateGradient did NOT converge "<<k<<" / "<< MaxIterations
|
||||
<<" residual "<< std::sqrt(cp / ssq)<< std::endl;
|
||||
SolverTimer.Stop();
|
||||
std::cout << GridLogMessage << "\tPreamble " << PreambleTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tConstruct " << ConstructTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tNorm " << NormTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tAssign " << AssignTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "\tSolver " << SolverTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage << "Solver breakdown "<<std::endl;
|
||||
std::cout << GridLogMessage << "\tMatrix " << MatrixTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogMessage<< "\tLinalg " << LinalgTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tInner " << InnerTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tAxpyNorm " << AxpyNormTimer.Elapsed() <<std::endl;
|
||||
std::cout << GridLogPerformance << "\t\tLinearComb " << LinearCombTimer.Elapsed() <<std::endl;
|
||||
|
||||
if (ErrorOnNoConverge) assert(0);
|
||||
IterationsToComplete = k;
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,230 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
γ5-Scalar Lanczos algorithm for γ5-Hermitian operators (Wilson Dirac).
|
||||
|
||||
Single-vector Lanczos using the γ5-inner product (u,v)_{γ5} = u†γ5v.
|
||||
Builds the Krylov space {q, D_W q, D_W² q, ...} and projects D_W onto it,
|
||||
producing a real tridiagonal matrix T_m whose eigenvalues approximate those
|
||||
of D_W. Complex conjugate pairs of D_W eigenvalues appear as complex
|
||||
eigenvalues of the real non-symmetric T_m.
|
||||
|
||||
Recurrence (G_k = sign(q_k†γ5 q_k) = ±1):
|
||||
r_k = D_W q_k − α_k q_k − β_sup[k-1] q_{k-1}
|
||||
β_sub[k] = √|r_k†γ5 r_k| (lower subdiag T_{k+1,k})
|
||||
β_sup[k] = β_sub[k] G_{k+1}/G_k (upper superdiag T_{k,k+1})
|
||||
q_{k+1} = r_k / β_sub[k]
|
||||
|
||||
T_m is real but not symmetric in general; eigenvalues via EigenSolver.
|
||||
|
||||
*************************************************************************************/
|
||||
#ifndef GRID_GAMMA5_SCALAR_LANCZOS_H
|
||||
#define GRID_GAMMA5_SCALAR_LANCZOS_H
|
||||
|
||||
#include <functional>
|
||||
#include <numeric>
|
||||
#include <iomanip>
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
template<class Field>
|
||||
class Gamma5ScalarLanczos {
|
||||
public:
|
||||
using Gamma5Func = std::function<void(const Field&, Field&)>;
|
||||
|
||||
private:
|
||||
typedef Eigen::MatrixXcd CMat;
|
||||
typedef Eigen::VectorXcd CVec;
|
||||
typedef Eigen::MatrixXd RMat;
|
||||
|
||||
LinearOperatorBase<Field>& Linop;
|
||||
GridBase* Grid_;
|
||||
Gamma5Func applyGamma5;
|
||||
RealD Tolerance;
|
||||
int nSteps;
|
||||
|
||||
std::vector<Field> basis;
|
||||
std::vector<RealD> alpha_; // diagonal of T_m
|
||||
std::vector<RealD> beta_sub_; // lower subdiagonal: T_{k+1,k}
|
||||
std::vector<RealD> beta_sup_; // upper superdiagonal: T_{k,k+1}
|
||||
std::vector<int> gsign_; // G_k = ±1
|
||||
|
||||
CVec evals_;
|
||||
std::vector<Field> evecs_;
|
||||
std::vector<RealD> residuals_;
|
||||
|
||||
public:
|
||||
bool doEvalCheck = false;
|
||||
|
||||
Gamma5ScalarLanczos(LinearOperatorBase<Field>& op, GridBase* grid,
|
||||
Gamma5Func g5, RealD tol = 1e-8)
|
||||
: Linop(op), Grid_(grid), applyGamma5(g5), Tolerance(tol), nSteps(0)
|
||||
{}
|
||||
|
||||
CVec getEvals() { return evals_; }
|
||||
std::vector<Field> getEvecs() { return evecs_; }
|
||||
std::vector<RealD> getResiduals() { return residuals_; }
|
||||
|
||||
// v0 : starting vector
|
||||
// maxSteps : maximum Lanczos steps
|
||||
// Nstop : target Ritz pairs to return (0 = all)
|
||||
// reorthog : full γ5-reorthogonalisation at each step
|
||||
// filter : eigenvalue selection criterion
|
||||
void operator()(const Field& v0, int maxSteps, int Nstop,
|
||||
bool reorthog = false, RitzFilter filter = EvalImNormSmall)
|
||||
{
|
||||
basis.clear(); alpha_.clear(); beta_sub_.clear(); beta_sup_.clear(); gsign_.clear();
|
||||
nSteps = 0;
|
||||
|
||||
// Normalise starting vector in γ5-norm: q_0 = v0 / √|v0†γ5 v0|
|
||||
Field q(Grid_); q = v0;
|
||||
Field g5q(Grid_);
|
||||
applyGamma5(q, g5q);
|
||||
RealD omega = std::real(toStdCmplx(innerProduct(g5q, q)));
|
||||
RealD beta0 = std::sqrt(std::abs(omega));
|
||||
assert(beta0 > 1e-14 && "starting vector has zero γ5-norm");
|
||||
q *= (1.0 / beta0);
|
||||
gsign_.push_back(omega >= 0 ? +1 : -1);
|
||||
basis.push_back(q);
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "Gamma5ScalarLanczos: start (v0†γ5 v0)=" << omega
|
||||
<< " G[0]=" << gsign_[0] << std::endl;
|
||||
|
||||
for (int k = 0; k < maxSteps; k++) {
|
||||
// ── Apply operator ─────────────────────────────────────────────────
|
||||
Field p(Grid_);
|
||||
Linop.Op(basis[k], p);
|
||||
|
||||
// ── α_k = (q_k†γ5 D_W q_k) / G_k (real) ─────────────────────────
|
||||
applyGamma5(basis[k], g5q);
|
||||
RealD a = std::real(toStdCmplx(innerProduct(g5q, p))) / RealD(gsign_[k]);
|
||||
alpha_.push_back(a);
|
||||
|
||||
// ── r = D_W q_k − α_k q_k − β_sup[k-1] q_{k-1} ───────────────────
|
||||
Field r(Grid_); r = p;
|
||||
r -= basis[k] * a;
|
||||
if (k > 0)
|
||||
r -= basis[k-1] * beta_sup_[k-1];
|
||||
|
||||
// ── Optional γ5-reorthogonalisation ────────────────────────────────
|
||||
if (reorthog) {
|
||||
for (int i = 0; i <= k; i++) {
|
||||
applyGamma5(basis[i], g5q);
|
||||
ComplexD c = toStdCmplx(innerProduct(g5q, r)) / RealD(gsign_[i]);
|
||||
r -= basis[i] * c;
|
||||
}
|
||||
}
|
||||
|
||||
// ── β_sub[k] = √|r†γ5 r| ───────────────────────────────────────────
|
||||
applyGamma5(r, g5q);
|
||||
omega = std::real(toStdCmplx(innerProduct(g5q, r)));
|
||||
RealD beta = std::sqrt(std::abs(omega));
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "Gamma5ScalarLanczos: k=" << k
|
||||
<< " alpha=" << a
|
||||
<< " beta=" << beta
|
||||
<< " G[k]=" << gsign_[k]
|
||||
<< " (r†γ5r)=" << omega << std::endl;
|
||||
|
||||
beta_sub_.push_back(beta);
|
||||
|
||||
if (beta < Tolerance) {
|
||||
std::cout << GridLogMessage
|
||||
<< "Gamma5ScalarLanczos: invariant subspace at step " << k << std::endl;
|
||||
nSteps = k + 1;
|
||||
break;
|
||||
}
|
||||
|
||||
int G_next = (omega >= 0) ? +1 : -1;
|
||||
gsign_.push_back(G_next);
|
||||
// β_sup[k] = T_{k,k+1} = β_sub[k] * G_{k+1} / G_k
|
||||
beta_sup_.push_back(beta * RealD(G_next) / RealD(gsign_[k]));
|
||||
|
||||
Field qnew(Grid_); qnew = r; qnew *= (1.0 / beta);
|
||||
basis.push_back(qnew);
|
||||
nSteps = k + 1;
|
||||
}
|
||||
|
||||
if (nSteps == 0) return;
|
||||
computeRitzPairs(nSteps, Nstop, filter);
|
||||
}
|
||||
|
||||
private:
|
||||
void computeRitzPairs(int m, int Nstop, RitzFilter filter)
|
||||
{
|
||||
// Assemble real tridiagonal T_m
|
||||
RMat Tm = RMat::Zero(m, m);
|
||||
for (int k = 0; k < m; k++) {
|
||||
Tm(k, k) = alpha_[k];
|
||||
if (k + 1 < m) {
|
||||
Tm(k+1, k) = beta_sub_[k];
|
||||
Tm(k, k+1) = beta_sup_[k];
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "Gamma5ScalarLanczos: T_m (" << m << "×" << m << "):" << std::endl;
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int j = 0; j < m; j++)
|
||||
std::cout << " " << std::setprecision(8) << std::setw(16) << Tm(i,j);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
Eigen::EigenSolver<RMat> es(Tm);
|
||||
CVec lambdas = es.eigenvalues();
|
||||
CMat Y = es.eigenvectors();
|
||||
|
||||
// Sort by filter criterion
|
||||
ComplexComparator cComp(filter);
|
||||
std::vector<int> idx(m);
|
||||
std::iota(idx.begin(), idx.end(), 0);
|
||||
std::sort(idx.begin(), idx.end(), [&](int a, int b){
|
||||
return cComp(toStdCmplx(lambdas(a)), toStdCmplx(lambdas(b)));
|
||||
});
|
||||
|
||||
int Nout = (Nstop > 0 && Nstop < m) ? Nstop : m;
|
||||
evals_.resize(Nout);
|
||||
evecs_.clear(); evecs_.reserve(Nout);
|
||||
residuals_.clear(); residuals_.reserve(Nout);
|
||||
|
||||
// Trailing β for residual estimate: β_sub[m-1] * |y_j[m-1]|
|
||||
RealD beta_trail = (m - 1 < (int)beta_sub_.size()) ? beta_sub_[m-1] : 0.0;
|
||||
|
||||
for (int ji = 0; ji < Nout; ji++) {
|
||||
int j = idx[ji];
|
||||
evals_(ji) = lambdas(j);
|
||||
CVec yj = Y.col(j);
|
||||
|
||||
// Ritz vector: u_j = Σ_k q_k y_j[k]
|
||||
Field uj(Grid_); uj = Zero();
|
||||
for (int k = 0; k < m && k < (int)basis.size(); k++)
|
||||
uj += basis[k] * toStdCmplx(yj(k));
|
||||
evecs_.push_back(uj);
|
||||
|
||||
RealD res = beta_trail * std::abs(toStdCmplx(yj(m-1)));
|
||||
if (!std::isfinite(res)) res = std::numeric_limits<RealD>::infinity();
|
||||
residuals_.push_back(res);
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< " Ritz[" << std::setw(3) << ji << "]"
|
||||
<< " lambda=" << evals_(ji)
|
||||
<< " |res|=" << res;
|
||||
|
||||
if (doEvalCheck) {
|
||||
Field w(Grid_);
|
||||
Linop.Op(uj, w);
|
||||
w -= uj * evals_(ji);
|
||||
RealD actual = std::sqrt(norm2(w));
|
||||
std::cout << " ||D_W u - λu||=" << actual;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
|
||||
#endif // GRID_GAMMA5_SCALAR_LANCZOS_H
|
||||
@@ -0,0 +1,719 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/iterative/HarmonicBlockKrylovSchur.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Peter Boyle <paboyle@ph.ed.ac.uk>
|
||||
Author: Chulwoo Jung <chulwoo@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_HARMONIC_BLOCKED_KRYLOV_SCHUR_H
|
||||
#define GRID_HARMONIC_BLOCKED_KRYLOV_SCHUR_H
|
||||
|
||||
#include <iomanip>
|
||||
#include <numeric>
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
/**
|
||||
* Block shift-targeted Krylov-Schur eigensolver.
|
||||
*
|
||||
* Algorithm
|
||||
* ---------
|
||||
* Uses a block Arnoldi factorisation:
|
||||
*
|
||||
* A V = V H + F B^dag (1)
|
||||
*
|
||||
* with V orthonormal (Nm columns), H the Nm×Nm block upper-Hessenberg
|
||||
* Rayleigh quotient, F the Nblock residual vectors and B the Nm×Nblock
|
||||
* coupling matrix.
|
||||
*
|
||||
* Thick restart
|
||||
* -------------
|
||||
* To target eigenvalues near shift σ, the Schur decomposition is computed
|
||||
* for the shifted Rayleigh quotient:
|
||||
*
|
||||
* (H - σI) = Q^dag S Q (2)
|
||||
*
|
||||
* Sorting the Schur values of (H - σI) by smallest |S(i,i)| = |λ - σ| and
|
||||
* retaining the leading Nk is equivalent to selecting the Ritz values of H
|
||||
* closest to σ. Since Q diagonalises H - σI (and hence H itself), the
|
||||
* rotated Rayleigh quotient is exactly upper triangular:
|
||||
*
|
||||
* H_new = Q H Q^dag = S + σI (upper triangular) (3)
|
||||
*
|
||||
* Truncation to Nk is therefore exact: the off-diagonal coupling block
|
||||
* H_new[Nk:, :Nk] = 0 by triangularity. The Krylov-Schur relation after
|
||||
* restart is exact and block Arnoldi resumes cleanly from F.
|
||||
*
|
||||
* Convergence
|
||||
* -----------
|
||||
* Convergence is declared when || B^H y_k || < Tolerance * approxLambdaMax
|
||||
* for each Ritz pair (λ_k, y_k) of the truncated H.
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* shift : target shift σ (default 0.0); Schur values sorted by |λ - σ|
|
||||
* Nblock : block size p
|
||||
* Nm : total Krylov dimension (must be divisible by Nblock)
|
||||
* Nk : total vectors to retain after each restart (must be divisible by Nblock, Nk < Nm)
|
||||
* Nstop : stop when this many eigenpairs converge
|
||||
* MaxIter : maximum outer (restart) iterations
|
||||
* Tolerance: relative convergence tolerance
|
||||
*
|
||||
* Usage
|
||||
* -----
|
||||
* HarmonicBlockKrylovSchur<Field> hbks(LinOp, Grid, tol, shift, EvalNormSmall);
|
||||
* std::vector<Field> v0(Nblock, Field(Grid));
|
||||
* // fill v0 with random starting vectors
|
||||
* hbks(v0, maxIter, Nm, Nk, Nstop, Nblock);
|
||||
* auto evals = hbks.getEvals();
|
||||
* auto evecs = hbks.getEvecs();
|
||||
*/
|
||||
template<class Field>
|
||||
class HarmonicBlockKrylovSchur {
|
||||
|
||||
protected:
|
||||
typedef Eigen::MatrixXcd CMat;
|
||||
typedef Eigen::VectorXcd CVec;
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Parameters
|
||||
//--------------------------------------------------------------------
|
||||
int Nblock;
|
||||
int Nm; // total Krylov dimension (multiple of Nblock)
|
||||
int Nk; // total vectors retained after restart (multiple of Nblock)
|
||||
int Nstop;
|
||||
int MaxIter;
|
||||
RealD Tolerance;
|
||||
ComplexD shift; // target shift σ
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Internal state
|
||||
//--------------------------------------------------------------------
|
||||
LinearOperatorBase<Field>& Linop;
|
||||
GridBase* Grid_;
|
||||
RitzFilter ritzFilter;
|
||||
|
||||
std::vector<Field> basis; // Nm*Nblock flat basis
|
||||
CMat H; // (Nm*Nblock)² block-Hessenberg Rayleigh quotient
|
||||
std::vector<Field> F; // Nblock residual vectors
|
||||
CMat B; // (Nm*Nblock) × Nblock coupling matrix
|
||||
RealD beta_k;
|
||||
RealD rtol;
|
||||
|
||||
CVec evals;
|
||||
CMat littleEvecs;
|
||||
std::vector<RealD> ritzEstimates;
|
||||
|
||||
public:
|
||||
std::vector<Field> evecs;
|
||||
bool doEvalCheck = false;
|
||||
bool useParityFlip = false;
|
||||
bool useGamma5 = false;
|
||||
std::function<void(const Field&, Field&)> gamma5Func;
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Constructor
|
||||
//--------------------------------------------------------------------
|
||||
HarmonicBlockKrylovSchur(LinearOperatorBase<Field>& _Linop, GridBase* _Grid,
|
||||
RealD _Tolerance, ComplexD _shift = 0.0,
|
||||
RitzFilter _rf = EvalNormSmall)
|
||||
: Linop(_Linop), Grid_(_Grid), Tolerance(_Tolerance), shift(_shift),
|
||||
ritzFilter(_rf),
|
||||
Nblock(-1), Nm(-1), Nk(-1), Nstop(-1), MaxIter(-1),
|
||||
beta_k(0.0), rtol(0.0)
|
||||
{}
|
||||
|
||||
virtual ~HarmonicBlockKrylovSchur() = default;
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Main entry point
|
||||
//--------------------------------------------------------------------
|
||||
virtual void operator()(const std::vector<Field>& v0, int _maxIter, int _Nm, int _Nk,
|
||||
int _Nstop, int _Nblock = 1, bool doubleOrthog = true,
|
||||
bool doVerify = false)
|
||||
{
|
||||
MaxIter = _maxIter;
|
||||
Nm = _Nm;
|
||||
Nk = _Nk;
|
||||
Nstop = _Nstop;
|
||||
Nblock = _Nblock;
|
||||
|
||||
{
|
||||
int divisor = 1;
|
||||
if (useParityFlip) divisor *= 2;
|
||||
if (useGamma5) divisor *= 2;
|
||||
assert(Nblock % divisor == 0 && (int)v0.size() >= Nblock / divisor);
|
||||
std::cout << GridLogMessage << "divisor= " << divisor << std::endl;
|
||||
|
||||
}
|
||||
assert(Nm % Nblock == 0);
|
||||
assert(Nk % Nblock == 0);
|
||||
assert(Nk < Nm);
|
||||
if (useGamma5) assert(gamma5Func && "useGamma5: gamma5Func must be set");
|
||||
|
||||
int N = Nm;
|
||||
|
||||
RealD approxLambdaMax = approxMaxEval(v0[0]);
|
||||
rtol = Tolerance * approxLambdaMax;
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur: approx max eval = " << approxLambdaMax
|
||||
<< ", rtol = " << rtol
|
||||
<< ", shift = " << shift << std::endl;
|
||||
|
||||
H = CMat::Zero(N, N);
|
||||
B = CMat::Zero(N, Nblock);
|
||||
|
||||
int start = 0;
|
||||
std::vector<Field> startBlock = expandStartBlock(v0);
|
||||
|
||||
for (int iter = 0; iter < MaxIter; iter++) {
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur: restart iteration " << iter << std::endl;
|
||||
|
||||
// ---- Block Arnoldi: extend from block 'start' to block Nm/Nblock ----
|
||||
blockArnoldiIteration(startBlock, Nm/Nblock, start, doubleOrthog);
|
||||
start = Nk/Nblock;
|
||||
|
||||
if (doVerify) {
|
||||
std::string lbl = "iter " + std::to_string(iter) + " after Arnoldi";
|
||||
verify(lbl);
|
||||
}
|
||||
|
||||
// ---- Schur decompose (H - σI) to select Schur vectors closest to σ ----
|
||||
// Sorting the Schur values of (H - σI) by |S(i,i)| = |λ - σ| gives the
|
||||
// Ritz values of H nearest the target shift without any matrix inversion.
|
||||
// Because Q diagonalises (H - σI), it also diagonalises H:
|
||||
// H_new = Q H Q^dag = S + σI (upper triangular)
|
||||
// Truncation is therefore exact.
|
||||
CMat Hshift = H - shift * CMat::Identity(N, N);
|
||||
ComplexSchurDecomposition schur(Hshift, false, ritzFilter);
|
||||
schur.schurReorder(Nk);
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur: Ritz values nearest shift (first Nk):" << std::endl;
|
||||
CMat S = schur.getMatrixS();
|
||||
for (int i = 0; i < Nk; i++)
|
||||
std::cout << GridLogMessage << " [" << i << "] " << S(i, i) + shift << std::endl;
|
||||
|
||||
CMat Q = schur.getMatrixQ();
|
||||
CMat Qt = Q.adjoint();
|
||||
|
||||
// ---- Rotate Krylov basis ----
|
||||
std::vector<Field> basis2;
|
||||
constructUR(basis2, basis, Qt, N);
|
||||
basis = basis2;
|
||||
|
||||
// ---- Update H and B ----
|
||||
// H_new = S + σI is upper triangular; off-diagonal block H_new[Nk:,:Nk] = 0
|
||||
H = S + shift * CMat::Identity(N, N);
|
||||
B = Q * B;
|
||||
|
||||
// ---- Truncate to Nk (exact: H upper triangular) ----
|
||||
int Nkeep = Nk;
|
||||
|
||||
CMat Htmp = H(Eigen::seqN(0, Nkeep), Eigen::seqN(0, Nkeep));
|
||||
H = CMat::Zero(N, N);
|
||||
H(Eigen::seqN(0, Nkeep), Eigen::seqN(0, Nkeep)) = Htmp;
|
||||
|
||||
std::vector<Field> basisTmp(basis.begin(), basis.begin() + Nkeep);
|
||||
basis = basisTmp;
|
||||
|
||||
CMat Btmp = B(Eigen::seqN(0, Nkeep), Eigen::all);
|
||||
B = CMat::Zero(N, Nblock);
|
||||
B(Eigen::seqN(0, Nkeep), Eigen::all) = Btmp;
|
||||
|
||||
beta_k = Btmp.norm();
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur: beta_k = " << beta_k << std::endl;
|
||||
|
||||
// Restart from F (exact: no discarded-basis correction needed)
|
||||
startBlock = F;
|
||||
|
||||
if (doVerify) {
|
||||
std::string lbl = "iter " + std::to_string(iter) + " after restart+truncation";
|
||||
verify(lbl);
|
||||
}
|
||||
|
||||
// ---- Eigensystem of truncated H for convergence ----
|
||||
CMat Hk = H(Eigen::seqN(0, Nkeep), Eigen::seqN(0, Nkeep));
|
||||
computeEigensystem(Hk, Nkeep);
|
||||
|
||||
int Nconv = converged(Nkeep);
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur: converged " << Nconv
|
||||
<< " / " << Nstop << std::endl;
|
||||
|
||||
if (Nconv >= Nstop || iter == MaxIter - 1) {
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur: done after " << iter
|
||||
<< " restarts, " << Nconv << " converged." << std::endl;
|
||||
std::cout << GridLogMessage << "Eigenvalues: " << evals.transpose() << std::endl;
|
||||
|
||||
if (doEvalCheck) {
|
||||
Field w(Grid_);
|
||||
for (int k = 0; k < (int)evecs.size(); k++) {
|
||||
Linop.Op(evecs[k], w);
|
||||
ComplexD eval_est = toStdCmplx(innerProduct(evecs[k], w));
|
||||
w -= eval_est * evecs[k];
|
||||
RealD res = std::sqrt(norm2(w));
|
||||
std::cout << GridLogMessage << "HarmonicBlockKrylovSchur: evec[" << k << "]"
|
||||
<< " eval_reported = " << evals[k]
|
||||
<< " eval_est = " << eval_est
|
||||
<< " || A v - eval_est * v || = " << res << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Accessors
|
||||
std::vector<Field> getEvecs() { return evecs; }
|
||||
CVec getEvals() { return evals; }
|
||||
std::vector<RealD> getRitzEstimates() { return ritzEstimates; }
|
||||
|
||||
static void parityFlippedField(const Field& v, Field& out) {
|
||||
GridCartesian* cgrid = dynamic_cast<GridCartesian*>(v.Grid());
|
||||
assert(cgrid != nullptr);
|
||||
GridRedBlackCartesian rbgrid(cgrid);
|
||||
Field veven(&rbgrid), vodd(&rbgrid);
|
||||
pickCheckerboard(Even, veven, v);
|
||||
pickCheckerboard(Odd, vodd, v);
|
||||
vodd = -vodd;
|
||||
setCheckerboard(out, veven);
|
||||
setCheckerboard(out, vodd);
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Verification: check A V = V H + F B^dag explicitly
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* Checks the block Arnoldi / Krylov-Schur decomposition
|
||||
*
|
||||
* A V = V H + F B^dag (KS)
|
||||
*
|
||||
* by explicit operator applications. H here is the standard Rayleigh
|
||||
* quotient, so the KS relation is the same as for BlockKrylovSchur.
|
||||
*
|
||||
* Prints:
|
||||
* - H (current Rayleigh quotient, nBasis × nBasis)
|
||||
* - B (coupling matrix, nBasis × Nblock)
|
||||
* - M (explicit inner product matrix <V | A V>)
|
||||
* - max |H[i,j] - M[i,j]| (should be O(machine epsilon))
|
||||
* - max |<V_i|V_j> - delta_ij| (orthonormality check)
|
||||
* - for each basis column j: || A v_j - V H[:,j] - F B[j,:]^* ||
|
||||
* - max |<V_i | F_t>| (F orthogonal to basis)
|
||||
*/
|
||||
void verify(const std::string& label = "")
|
||||
{
|
||||
int nBasis = (int)basis.size();
|
||||
int nF = (int)F.size();
|
||||
|
||||
if (nBasis == 0) {
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur::verify [" << label
|
||||
<< "]: basis is empty." << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "======== HarmonicBlockKrylovSchur::verify [" << label << "] ========" << std::endl;
|
||||
std::cout << GridLogMessage
|
||||
<< " nBasis = " << nBasis << " Nblock = " << Nblock
|
||||
<< " nF = " << nF << std::endl;
|
||||
|
||||
// ---- Print H ----
|
||||
std::cout << GridLogMessage << "H (" << nBasis << " x " << nBasis << "):" << std::endl;
|
||||
for (int i = 0; i < nBasis; i++) {
|
||||
for (int j = 0; j < nBasis; j++)
|
||||
std::cout << " " << std::setprecision(4) << std::setw(14) << H(i, j);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
// ---- Print B ----
|
||||
std::cout << GridLogMessage << "B (" << nBasis << " x " << nF << "):" << std::endl;
|
||||
for (int i = 0; i < nBasis; i++) {
|
||||
for (int t = 0; t < nF; t++)
|
||||
std::cout << " " << std::setprecision(4) << std::setw(14) << B(i, t);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
// ---- Compute M[i,j] = <basis[i] | A basis[j]> ----
|
||||
CMat M = CMat::Zero(nBasis, nBasis);
|
||||
Field w(Grid_);
|
||||
for (int j = 0; j < nBasis; j++) {
|
||||
Linop.Op(basis[j], w);
|
||||
for (int i = 0; i < nBasis; i++)
|
||||
M(i, j) = toStdCmplx(innerProduct(basis[i], w));
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage << "M = <V|AV> (" << nBasis << " x " << nBasis << "):" << std::endl;
|
||||
for (int i = 0; i < nBasis; i++) {
|
||||
for (int j = 0; j < nBasis; j++)
|
||||
std::cout << " " << std::setprecision(4) << std::setw(14) << M(i, j);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
// ---- max |H - M| ----
|
||||
RealD maxHM = 0.0;
|
||||
for (int i = 0; i < nBasis; i++)
|
||||
for (int j = 0; j < nBasis; j++)
|
||||
maxHM = std::max(maxHM, std::abs(H(i,j) - M(i,j)));
|
||||
std::cout << GridLogMessage
|
||||
<< " max |H[i,j] - M[i,j]| = " << maxHM << std::endl;
|
||||
|
||||
// ---- Check orthonormality of basis ----
|
||||
CMat G = CMat::Zero(nBasis, nBasis);
|
||||
for (int i = 0; i < nBasis; i++)
|
||||
for (int j = 0; j < nBasis; j++)
|
||||
G(i, j) = toStdCmplx(innerProduct(basis[i], basis[j]));
|
||||
CMat Gerr = G - CMat::Identity(nBasis, nBasis);
|
||||
std::cout << GridLogMessage
|
||||
<< " max |<V_i|V_j> - delta_ij| = " << Gerr.cwiseAbs().maxCoeff() << std::endl;
|
||||
|
||||
// ---- Per-column residual: || A v_j - V H[:,j] - F B[j,:]^* || ----
|
||||
RealD maxColDev = 0.0;
|
||||
for (int j = 0; j < nBasis; j++) {
|
||||
Linop.Op(basis[j], w);
|
||||
|
||||
// subtract V H[:,j]
|
||||
for (int i = 0; i < nBasis; i++)
|
||||
w -= basis[i] * H(i, j);
|
||||
|
||||
// subtract F B[j,:]^* (F[t] * conj(B[j,t]))
|
||||
for (int t = 0; t < nF; t++)
|
||||
w -= F[t] * std::conj(B(j, t));
|
||||
|
||||
RealD dev = std::sqrt(norm2(w));
|
||||
std::cout << GridLogMessage
|
||||
<< " || A v[" << j << "] - V H[:,j] - F B[j,:]* || = " << dev << std::endl;
|
||||
maxColDev = std::max(maxColDev, dev);
|
||||
}
|
||||
std::cout << GridLogMessage
|
||||
<< " max column deviation = " << maxColDev << std::endl;
|
||||
|
||||
// ---- Check F block orthogonality against basis ----
|
||||
if (nF > 0) {
|
||||
RealD maxFV = 0.0;
|
||||
for (int t = 0; t < nF; t++)
|
||||
for (int i = 0; i < nBasis; i++) {
|
||||
RealD ip = std::abs(toStdCmplx(innerProduct(basis[i], F[t])));
|
||||
maxFV = std::max(maxFV, ip);
|
||||
}
|
||||
std::cout << GridLogMessage
|
||||
<< " max |<V_i | F_t>| (should be ~0) = " << maxFV << std::endl;
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "======== end verify ========" << std::endl;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Starting-block expansion (parity flip / gamma5 partners)
|
||||
//--------------------------------------------------------------------
|
||||
// Expands Nblock/divisor seed vectors into the full Nblock starting
|
||||
// block, pairing each seed with its parity-flipped and/or gamma5
|
||||
// partners. Requires Nblock, Grid_ and the flags to be set.
|
||||
std::vector<Field> expandStartBlock(const std::vector<Field>& v0)
|
||||
{
|
||||
int divisor = (useParityFlip ? 2 : 1) * (useGamma5 ? 2 : 1);
|
||||
std::vector<Field> startBlock;
|
||||
startBlock.reserve(Nblock);
|
||||
for (int i = 0; i < Nblock / divisor; i++) {
|
||||
std::vector<Field> group;
|
||||
group.push_back(v0[i]);
|
||||
if (useParityFlip) {
|
||||
int n = (int)group.size();
|
||||
for (int j = 0; j < n; j++) {
|
||||
Field fp(Grid_);
|
||||
parityFlippedField(group[j], fp);
|
||||
group.push_back(std::move(fp));
|
||||
}
|
||||
}
|
||||
if (useGamma5) {
|
||||
int n = (int)group.size();
|
||||
for (int j = 0; j < n; j++) {
|
||||
Field g5v(Grid_);
|
||||
gamma5Func(group[j], g5v);
|
||||
group.push_back(std::move(g5v));
|
||||
}
|
||||
}
|
||||
for (auto& f : group) startBlock.push_back(std::move(f));
|
||||
}
|
||||
return startBlock;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Block Arnoldi iteration
|
||||
//--------------------------------------------------------------------
|
||||
void blockArnoldiIteration(std::vector<Field>& startBlock, int endBlock,
|
||||
int startIdx, bool doubleOrthog)
|
||||
{
|
||||
int N = Nm;
|
||||
|
||||
if (startIdx == 0) {
|
||||
basis.clear();
|
||||
F.clear();
|
||||
H = CMat::Zero(N, N);
|
||||
B = CMat::Zero(N, Nblock);
|
||||
|
||||
std::vector<Field> V0 = startBlock;
|
||||
blockOrthonormalise(V0);
|
||||
for (auto& v : V0) basis.push_back(v);
|
||||
} else {
|
||||
// Append the new starting block to the retained basis.
|
||||
//
|
||||
// The exact truncated KS relation is A V_k = V_k H_k + F B_k^dag,
|
||||
// so the coupling rows are H[Nkeep+t, j] = conj(B_k[j,t]).
|
||||
// Since H_new = S + σI is upper triangular, the off-diagonal block
|
||||
// H_new[Nkeep:, :Nkeep] = 0 and the restart from F is exact.
|
||||
int Nkeep = startIdx * Nblock;
|
||||
for (auto& v : startBlock) basis.push_back(v);
|
||||
|
||||
// Fill restart coupling rows into H (exact: H_new is upper triangular,
|
||||
// so B encodes the only non-zero coupling to the new block).
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
for (int j = 0; j < Nkeep; j++)
|
||||
H(Nkeep + t, j) = std::conj(B(j, t));
|
||||
|
||||
// Zero out B for the retained columns now that the coupling is in H
|
||||
for (int j = 0; j < Nkeep; j++)
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
B(j, t) = 0.0;
|
||||
}
|
||||
|
||||
for (int k = startIdx; k < endBlock; k++)
|
||||
blockArnoldiStep(k, doubleOrthog);
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// One block Arnoldi step
|
||||
//--------------------------------------------------------------------
|
||||
void blockArnoldiStep(int k, bool doubleOrthog)
|
||||
{
|
||||
int kBase = k * Nblock;
|
||||
int prevN = kBase + Nblock;
|
||||
int N = Nm;
|
||||
|
||||
std::vector<Field> W(Nblock, Field(Grid_));
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
Linop.Op(basis[kBase + t], W[t]);
|
||||
|
||||
// Full reorthogonalisation against all current basis vectors
|
||||
for (int pass = 0; pass < (doubleOrthog ? 2 : 1); pass++) {
|
||||
for (int i = 0; i < prevN; i++) {
|
||||
for (int t = 0; t < Nblock; t++) {
|
||||
ComplexD coeff = innerProduct(basis[i], W[t]);
|
||||
if (pass == 0)
|
||||
H(i, kBase + t) = toStdCmplx(coeff);
|
||||
else
|
||||
H(i, kBase + t) += toStdCmplx(coeff);
|
||||
W[t] -= coeff * basis[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
F = W;
|
||||
|
||||
if (k == Nm/Nblock - 1) {
|
||||
// Last block: record coupling in B as R^H (Hermitian conjugate of QR factor)
|
||||
// KS relation requires B[kBase+t, s] = conj(R[s,t])
|
||||
CMat R = blockQR(F);
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
for (int s = 0; s < Nblock; s++)
|
||||
B(kBase + t, s) = std::conj(R(s, t)); // B_block = R^H
|
||||
beta_k = R.norm();
|
||||
return;
|
||||
}
|
||||
|
||||
// Not last: QR the residual, extend basis
|
||||
CMat R = blockQR(F);
|
||||
|
||||
int nextBase = (k + 1) * Nblock;
|
||||
for (int i = 0; i < Nblock; i++)
|
||||
for (int j = 0; j < Nblock; j++)
|
||||
H(nextBase + i, kBase + j) = R(i, j);
|
||||
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
basis.push_back(F[t]);
|
||||
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Block QR (modified Gram-Schmidt within the block)
|
||||
//--------------------------------------------------------------------
|
||||
CMat blockQR(std::vector<Field>& W)
|
||||
{
|
||||
CMat R = CMat::Zero(Nblock, Nblock);
|
||||
const RealD deflThresh = 1e-14;
|
||||
|
||||
for (int j = 0; j < Nblock; j++) {
|
||||
for (int i = 0; i < j; i++) {
|
||||
ComplexD coeff = innerProduct(W[i], W[j]);
|
||||
R(i, j) = toStdCmplx(coeff);
|
||||
W[j] -= coeff * W[i];
|
||||
}
|
||||
RealD nrm = std::sqrt(norm2(W[j]));
|
||||
R(j, j) = nrm;
|
||||
if (nrm > deflThresh) {
|
||||
W[j] *= (1.0 / nrm);
|
||||
} else {
|
||||
W[j] = Zero();
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur: deflation at block column " << j
|
||||
<< " (norm = " << nrm << ")" << std::endl;
|
||||
}
|
||||
}
|
||||
return R;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Orthonormalise starting block
|
||||
//--------------------------------------------------------------------
|
||||
void blockOrthonormalise(std::vector<Field>& V)
|
||||
{
|
||||
for (int j = 0; j < (int)V.size(); j++) {
|
||||
for (int i = 0; i < j; i++) {
|
||||
ComplexD c = innerProduct(V[i], V[j]);
|
||||
V[j] -= c * V[i];
|
||||
}
|
||||
RealD nrm = std::sqrt(norm2(V[j]));
|
||||
assert(nrm > 1e-14);
|
||||
V[j] *= (1.0 / nrm);
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Basis rotation: UR[i] = sum_j U[j] * R(j,i)
|
||||
//--------------------------------------------------------------------
|
||||
void constructUR(std::vector<Field>& UR, std::vector<Field>& U,
|
||||
CMat& R, int N)
|
||||
{
|
||||
UR.clear();
|
||||
Field tmp(Grid_);
|
||||
for (int i = 0; i < N; i++) {
|
||||
tmp = Zero();
|
||||
for (int j = 0; j < N; j++)
|
||||
tmp += U[j] * R(j, i);
|
||||
UR.push_back(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Eigensystem of the truncated H (not Hhat)
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* Eigenvalues of H_k are the standard Ritz values in the retained
|
||||
* subspace. After convergence has been declared via harmonic estimates,
|
||||
* the final reported eigenvalues and vectors come from H_k (not Hhat_k),
|
||||
* since H_k contains the true projected operator.
|
||||
*/
|
||||
void computeEigensystem(CMat& Hk, int Nkeep)
|
||||
{
|
||||
Eigen::ComplexEigenSolver<CMat> es;
|
||||
es.compute(Hk);
|
||||
|
||||
// Sort to match schurReorder ordering.
|
||||
int n = es.eigenvalues().size();
|
||||
ComplexComparator cComp(ritzFilter);
|
||||
std::vector<int> idx(n);
|
||||
std::iota(idx.begin(), idx.end(), 0);
|
||||
std::sort(idx.begin(), idx.end(), [&](int a, int b){
|
||||
return cComp(toStdCmplx(es.eigenvalues()(a)), toStdCmplx(es.eigenvalues()(b)));
|
||||
});
|
||||
|
||||
evals.resize(n);
|
||||
littleEvecs.resize(n, n);
|
||||
for (int k = 0; k < n; k++) {
|
||||
evals(k) = es.eigenvalues()(idx[k]);
|
||||
littleEvecs.col(k) = es.eigenvectors().col(idx[k]);
|
||||
}
|
||||
|
||||
evecs.clear();
|
||||
for (int k = 0; k < Nkeep; k++) {
|
||||
CVec vec = littleEvecs.col(k);
|
||||
Field tmp(Grid_);
|
||||
tmp = Zero();
|
||||
for (int j = 0; j < (int)basis.size() && j < Nkeep; j++)
|
||||
tmp += vec[j] * basis[j];
|
||||
evecs.push_back(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Convergence check
|
||||
//--------------------------------------------------------------------
|
||||
/**
|
||||
* Ritz estimate for eigenpair k: || B^H y_k ||
|
||||
* where y_k is the k-th eigenvector of the truncated H.
|
||||
* The same bound applies whether using Ritz or harmonic Ritz restart.
|
||||
*/
|
||||
int converged(int Nkeep)
|
||||
{
|
||||
ritzEstimates.clear();
|
||||
int Nconv = 0;
|
||||
|
||||
CMat Bk = B(Eigen::seqN(0, Nkeep), Eigen::all);
|
||||
|
||||
for (int k = 0; k < Nkeep; k++) {
|
||||
CVec yk = littleEvecs.col(k);
|
||||
CVec Bty = Bk.adjoint() * yk;
|
||||
RealD res = Bty.norm();
|
||||
ritzEstimates.push_back(res);
|
||||
std::cout << GridLogMessage
|
||||
<< "HarmonicBlockKrylovSchur: Ritz estimate[" << k
|
||||
<< "] = " << res << " eval = " << evals[k] << std::endl;
|
||||
if (res < rtol) Nconv++;
|
||||
else break;
|
||||
}
|
||||
return Nconv;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Approximate maximum eigenvalue (power iteration)
|
||||
//--------------------------------------------------------------------
|
||||
RealD approxMaxEval(const Field& v0, int MAX_ITER = 50)
|
||||
{
|
||||
assert(norm2(v0) > 1e-8);
|
||||
RealD lam = 0.0, denom = std::sqrt(norm2(v0));
|
||||
Field vcur(Grid_), vtmp(Grid_);
|
||||
vcur = v0;
|
||||
for (int i = 0; i < MAX_ITER; i++) {
|
||||
Linop.Op(vcur, vtmp);
|
||||
vcur = vtmp;
|
||||
RealD num = std::sqrt(norm2(vcur));
|
||||
lam = num / denom;
|
||||
denom = num;
|
||||
}
|
||||
return lam;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
|
||||
#endif // GRID_HARMONIC_BLOCKED_KRYLOV_SCHUR_H
|
||||
@@ -53,6 +53,18 @@ enum IRLdiagonalisation {
|
||||
IRLdiagonaliseWithEigen
|
||||
};
|
||||
|
||||
enum IRLeigsort {
|
||||
IRLeigsortMax,
|
||||
IRLeigsortSqMin
|
||||
};
|
||||
|
||||
#if 0
|
||||
bool square_comp(RealD a, RealD b){
|
||||
if (a*a<b*b) return true;
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
template<class Field> class ImplicitlyRestartedLanczosHermOpTester : public ImplicitlyRestartedLanczosTester<Field>
|
||||
{
|
||||
public:
|
||||
@@ -119,9 +131,10 @@ class ImplicitlyRestartedLanczos {
|
||||
/////////////////////////
|
||||
// Constructor
|
||||
/////////////////////////
|
||||
|
||||
public:
|
||||
public:
|
||||
IRLeigsort EigSort;
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////
|
||||
// PAB:
|
||||
//////////////////////////////////////////////////////////////////
|
||||
@@ -154,6 +167,7 @@ public:
|
||||
Nstop(_Nstop) , Nk(_Nk), Nm(_Nm),
|
||||
eresid(_eresid), betastp(_betastp),
|
||||
MaxIter(_MaxIter) , MinRestart(_MinRestart),
|
||||
EigSort(IRLeigsortMax),
|
||||
orth_period(_orth_period), diagonalisation(_diagonalisation) { };
|
||||
|
||||
ImplicitlyRestartedLanczos(LinearFunction<Field> & PolyOp,
|
||||
@@ -170,6 +184,7 @@ public:
|
||||
Nstop(_Nstop) , Nk(_Nk), Nm(_Nm),
|
||||
eresid(_eresid), betastp(_betastp),
|
||||
MaxIter(_MaxIter) , MinRestart(_MinRestart),
|
||||
EigSort(IRLeigsortMax),
|
||||
orth_period(_orth_period), diagonalisation(_diagonalisation) { };
|
||||
|
||||
////////////////////////////////
|
||||
@@ -316,8 +331,12 @@ until convergence
|
||||
// sorting
|
||||
//////////////////////////////////
|
||||
eval2_copy = eval2;
|
||||
// if (EigSort==IRLeigsortMax)
|
||||
// std::partial_sort(eval2.begin(),eval2.begin()+Nm,eval2.end(),square_comp);
|
||||
// else
|
||||
std::partial_sort(eval2.begin(),eval2.begin()+Nm,eval2.end(),std::greater<RealD>());
|
||||
std::cout<<GridLogIRL <<" evals sorted "<<std::endl;
|
||||
// eval2_copy = eval2;
|
||||
const int chunk=8;
|
||||
for(int io=0; io<k2;io+=chunk){
|
||||
std::cout<<GridLogIRL << "eval "<< std::setw(3) << io ;
|
||||
@@ -333,6 +352,7 @@ until convergence
|
||||
//////////////////////////////////
|
||||
Qt = Eigen::MatrixXd::Identity(Nm,Nm);
|
||||
for(int ip=k2; ip<Nm; ++ip){
|
||||
// std::cout<<GridLogIRL <<"QR decompose "<<eval2[ip]<<std::endl;
|
||||
QR_decomp(eval,lme,Nm,Nm,Qt,eval2[ip],k1,Nm);
|
||||
}
|
||||
std::cout<<GridLogIRL <<"QR decomposed "<<std::endl;
|
||||
@@ -375,7 +395,8 @@ until convergence
|
||||
|
||||
// power of two search pattern; not every evalue in eval2 is assessed.
|
||||
int allconv =1;
|
||||
for(int jj = 1; jj<=Nstop; jj*=2){
|
||||
// for(int jj = 1; jj<=Nstop; jj*=2){
|
||||
for(int jj = 1; jj<=Nstop; jj++){
|
||||
int j = Nstop-jj;
|
||||
RealD e = eval2_copy[j]; // Discard the evalue
|
||||
basisRotateJ(B,evec,Qt,j,0,Nk,Nm);
|
||||
|
||||
@@ -0,0 +1,994 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/iterative/KrylovSchur.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Peter Boyle <paboyle@ph.ed.ac.uk>
|
||||
Author: paboyle <paboyle@ph.ed.ac.uk>
|
||||
Author: Patrick Oare <poare@bnl.gov>
|
||||
Author: Chulwoo Jung <chulwoo@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_KRYLOVSCHUR_H
|
||||
#define GRID_KRYLOVSCHUR_H
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
#if defined(GRID_CUDA) || defined(GRID_HIP)
|
||||
using thrust::abs;
|
||||
using thrust::conj;
|
||||
inline std::complex<double> toStdCmplx(const ComplexD& c) { return {c.real(), c.imag()}; }
|
||||
#else
|
||||
using std::abs;
|
||||
using std::conj;
|
||||
inline const ComplexD& toStdCmplx(const ComplexD& c) { return c; }
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Small dense coefficient matrix of ComplexD (thrust::complex on GPU builds)
|
||||
* for passing to basisRotate, whose device kernel cannot multiply Grid tensors
|
||||
* by std::complex. Must be namespace-scope: nvcc rejects function-local types
|
||||
* as template arguments to functions containing extended device lambdas.
|
||||
*/
|
||||
struct KSCoeffMat {
|
||||
std::vector<ComplexD> a; int n;
|
||||
KSCoeffMat(int _n) : a(_n*_n), n(_n) {}
|
||||
ComplexD& operator()(int i, int j) { return a[i*n+j]; }
|
||||
const ComplexD& operator()(int i, int j) const { return a[i*n+j]; }
|
||||
};
|
||||
|
||||
/**
|
||||
* Options for which Ritz values to keep in implicit restart. TODO move this and utilities into a new file
|
||||
*/
|
||||
enum RitzFilter {
|
||||
EvalNormSmall, // Keep evals with smallest norm
|
||||
EvalNormLarge, // Keep evals with largest norm
|
||||
EvalReSmall, // Keep evals with smallest real part
|
||||
EvalReLarge, // Keep evals with largest real part
|
||||
EvalReNormLarge, // Keep evals with largest real part
|
||||
EvalImSmall, // Keep evals with smallest imaginary part
|
||||
EvalImLarge, // Keep evals with largest imaginary part
|
||||
EvalImNormSmall, // Keep evals with smallest |imaginary| part
|
||||
EvalImNormLarge, // Keep evals with largest |imaginary| part
|
||||
};
|
||||
|
||||
/** Selects the RitzFilter corresponding to the input string. */
|
||||
inline RitzFilter selectRitzFilter(std::string s) {
|
||||
if (s == "EvalNormSmall") { return EvalNormSmall; } else
|
||||
if (s == "EvalNormLarge") { return EvalNormLarge; } else
|
||||
if (s == "EvalReSmall") { return EvalReSmall; } else
|
||||
if (s == "EvalReLarge") { return EvalReLarge; } else
|
||||
if (s == "EvalReNormLarge") { return EvalReNormLarge; } else
|
||||
if (s == "EvalImSmall") { return EvalImSmall; } else
|
||||
if (s == "EvalImLarge") { return EvalImLarge; } else
|
||||
if (s == "EvalImNormSmall") { return EvalImNormSmall; } else
|
||||
if (s == "EvalImNormLarge") { return EvalImNormLarge; } else
|
||||
{ assert(0); }
|
||||
}
|
||||
|
||||
/** Returns a string saying which RitzFilter it is. */
|
||||
inline std::string rfToString(RitzFilter RF) {
|
||||
switch (RF) {
|
||||
case EvalNormSmall:
|
||||
return "EvalNormSmall";
|
||||
case EvalNormLarge:
|
||||
return "EvalNormLarge";
|
||||
case EvalReSmall:
|
||||
return "EvalReSmall";
|
||||
case EvalReLarge:
|
||||
return "EvalReLarge";
|
||||
case EvalReNormLarge:
|
||||
return "EvalReNormLarge";
|
||||
case EvalImSmall:
|
||||
return "EvalImSmall";
|
||||
case EvalImLarge:
|
||||
return "EvalImLarge";
|
||||
case EvalImNormSmall:
|
||||
return "EvalImNormSmall";
|
||||
case EvalImNormLarge:
|
||||
return "EvalImNormLarge";
|
||||
default:
|
||||
assert(0);
|
||||
}
|
||||
}
|
||||
|
||||
// Select comparison function from RitzFilter
|
||||
struct ComplexComparator
|
||||
{
|
||||
RitzFilter RF;
|
||||
ComplexComparator (RitzFilter _rf) : RF(_rf) {}
|
||||
bool operator()(std::complex<double> z1, std::complex<double> z2) {
|
||||
RealD tmp1=std::abs(std::imag(z1));
|
||||
RealD tmp2=std::abs(std::imag(z2));
|
||||
if ( std::abs(std::real(z1)) >2.) tmp1 += 100.;
|
||||
if ( std::abs(std::real(z2)) >2.) tmp2 += 100.;
|
||||
switch (RF) {
|
||||
case EvalNormSmall:
|
||||
return std::abs(z1) < std::abs(z2);
|
||||
case EvalNormLarge:
|
||||
return std::abs(z1) > std::abs(z2);
|
||||
case EvalReSmall:
|
||||
return std::real(z1) < std::real(z2); // DELETE THE ABS HERE!!!
|
||||
case EvalReLarge:
|
||||
return std::real(z1) > std::real(z2);
|
||||
case EvalReNormLarge:
|
||||
return std::abs(std::real(z1)) < std::abs(std::real(z2));
|
||||
case EvalImSmall:
|
||||
return std::imag(z1) < std::imag(z2);
|
||||
case EvalImLarge:
|
||||
return std::imag(z1) > std::imag(z2);
|
||||
case EvalImNormSmall:
|
||||
// return std::abs(std::imag(z1)) < std::abs(std::imag(z2));
|
||||
return tmp1 < tmp2 ;
|
||||
case EvalImNormLarge:
|
||||
return std::abs(std::imag(z1)) > std::abs(std::imag(z2));
|
||||
default:
|
||||
assert(0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Computes a complex Schur decomposition of a complex matrix A using Eigen's matrix library. The Schur decomposition,
|
||||
* A = Q^\dag S Q
|
||||
* factorizes A into a unitary matrix Q and an upper triangular matrix S. The eigenvalues of A lie on the diagonal of the upper triangular matrix S.
|
||||
* The Schur decomposition is not unique: in particular, any ordering of the eigenvalues of A can be used as the diagonal of the matrix S.
|
||||
* This class supports eigenvalue reordering by swapping two adjacent eigenvalues with a unitary transformation.
|
||||
*/
|
||||
class ComplexSchurDecomposition {
|
||||
|
||||
private:
|
||||
|
||||
typedef Eigen::MatrixXcd CMat;
|
||||
|
||||
CMat A; // Matrix to decompose, A = Q^\dag S Q
|
||||
CMat Q; // Unitary matrix Q
|
||||
CMat S; // Upper triangular matrix S
|
||||
|
||||
// Placeholders for Givens rotation
|
||||
CMat Givens; // Givens rotation
|
||||
ComplexD s; // off-diagonal element
|
||||
ComplexD lam1; // First eval for swap
|
||||
ComplexD lam2; // Second eval for swap
|
||||
ComplexD phi; // phase of s
|
||||
RealD r; // norm of s and lam2 - lam1
|
||||
|
||||
int Nm; // size of matrix problem
|
||||
|
||||
ComplexComparator cCompare; // function to sort the Schur matrix.
|
||||
|
||||
public:
|
||||
|
||||
/**
|
||||
* If the input matrix _A is in Hessenberg form (upper triangular + first subdiagonal non-zero), then the Schur
|
||||
* decomposition is easier to compute.
|
||||
*/
|
||||
ComplexSchurDecomposition(CMat _A, bool isHess, RitzFilter ritzFilter = EvalReSmall) : A(_A), Nm (_A.rows()), cCompare (ritzFilter)
|
||||
{
|
||||
Eigen::ComplexSchur<CMat> schur (Nm);
|
||||
if (isHess) {
|
||||
schur.computeFromHessenberg(_A, CMat::Identity(Nm, Nm), true);
|
||||
} else {
|
||||
schur.compute(_A, true);
|
||||
}
|
||||
S = schur.matrixT();
|
||||
Q = schur.matrixU().adjoint(); // Eigen computes A = Q S Q^\dag, we want A = Q^\dag S Q
|
||||
}
|
||||
|
||||
// Getters
|
||||
int getNm() { return Nm; } // size of matrix problem
|
||||
CMat getMatrixA() { return A; } // matrix for decomposition
|
||||
CMat getMatrixQ() { return Q; } // unitary matrix Q
|
||||
CMat getMatrixS() { return S; } // Schur matrix (upper triangular) S
|
||||
CMat getRitz() { return S.diagonal(); }
|
||||
|
||||
/**
|
||||
* Checks the Schur decomposition A = Q^\dag S Q holds for the computed matrices. Returns if the relative
|
||||
* Frobenius norm || A - Q^\dag S Q || / || A || is less than rtol.
|
||||
*/
|
||||
bool checkDecomposition(RealD rtol = 1e-8) {
|
||||
RealD Anorm = A.norm();
|
||||
if (Anorm < rtol) {
|
||||
std::cout << GridLogMessage << "Zero matrix" << std::endl;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::cout << GridLogDebug << "S = " << std::endl << S << std::endl;
|
||||
std::cout << GridLogDebug << "Q = " << std::endl << Q << std::endl;
|
||||
|
||||
CMat A2 = Q.adjoint() * S * Q;
|
||||
std::cout << GridLogDebug << "Q^dag S Q = " << std::endl << A2 << std::endl;
|
||||
RealD dA = (A - A2).norm() / Anorm;
|
||||
return (dA < rtol);
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps the components on the diagonal of the Schur matrix at index i with index i + 1.
|
||||
* Updates the orthogonal matrix Q accordingly.
|
||||
*/
|
||||
void swapEvals(int i) {
|
||||
|
||||
assert(0 <= i && i <= Nm - 1); // can only swap blocks with upper left index between 0 and Nm - 1
|
||||
|
||||
// get parameters for rotation
|
||||
s = S(i, i+1);
|
||||
lam1 = S(i, i);
|
||||
lam2 = S(i+1, i+1);
|
||||
phi = s / abs(s);
|
||||
r = std::sqrt(std::pow(abs(s), 2) + std::pow(abs(lam2 - lam1), 2));
|
||||
|
||||
// // Original code which performs Givens rotations by manual matrix multiplication
|
||||
// // compute Givens rotation corresponding to these parameters
|
||||
// Givens = CMat::Identity(Nm, Nm);
|
||||
// Givens(i, i) = std::abs(s) / r;
|
||||
// Givens(i+1, i+1) = Givens(i, i);
|
||||
// Givens(i, i+1) = (phi / r) * std::conj(lam2 - lam1);
|
||||
// Givens(i+1, i) = -std::conj(Givens(i, i+1));
|
||||
// // rotate Schur matrix and unitary change of basis matrix Q
|
||||
// S = Givens * S * Givens.adjoint();
|
||||
// Q = Givens * Q;
|
||||
|
||||
// Modified code
|
||||
Givens = CMat::Identity(2, 2);
|
||||
Givens(0, 0) = abs(s) / r;
|
||||
Givens(1, 1) = Givens(0, 0);
|
||||
Givens(0, 1) = (phi / r) * conj(lam2 - lam1);
|
||||
Givens(1, 0) = -conj(Givens(0, 1));
|
||||
|
||||
// TODO: make sure these are correct
|
||||
Eigen::MatrixXcd tmp;
|
||||
tmp = Givens * S.block(i, 0, 2, Nm);
|
||||
S.block(i, 0, 2, Nm) = tmp;
|
||||
|
||||
// S_{:, i:i+2} = S.block<Nm, 2>(0, i);
|
||||
tmp = S.block(0, i, Nm, 2) * Givens.adjoint();
|
||||
S.block(0, i, Nm, 2) = tmp;
|
||||
|
||||
// Q_{i:i+2, :} = Q.block<2, Nm>(i, 0);
|
||||
tmp = Givens * Q.block(i, 0, 2, Nm);
|
||||
Q.block(i, 0, 2, Nm) = tmp;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reorders a Schur matrix &Schur to have the Ritz values that we would like to keep for
|
||||
* restart as the first Nk elements on the diagonal.
|
||||
*
|
||||
* This algorithm is implemented as Nk iterations of a a reverse bubble sort with comparator compare.
|
||||
* TODO: pass in compare function as an argument, default to compare with <.
|
||||
*/
|
||||
// void schurReorder(int Nk, std::function compare) {
|
||||
void schurReorder(int Nk) {
|
||||
std::cout << GridLogMessage << "schurReorder start " << std::endl;
|
||||
int nswap=0;
|
||||
for (int i = 0; i < Nk; i++) {
|
||||
for (int k = 0; k <= Nm - 2; k++) {
|
||||
int idx = Nm - 2 - k;
|
||||
// TODO use RitzFilter enum here
|
||||
// if (std::abs(S(idx, idx)) < std::abs(S(idx+1, idx+1))) { // sort by largest modulus of eigenvalue
|
||||
// if (std::real(S(idx, idx)) > std::real(S(idx+1, idx+1))) { // sort by smallest real eigenvalue
|
||||
if ( cCompare(S(idx+1, idx+1), S(idx, idx)) ) { // sort by largest modulus of eigenvalue
|
||||
swapEvals(idx);
|
||||
nswap++;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::cout << GridLogMessage << "schurReorder end "<< nswap << std::endl;
|
||||
for (int i = 0; i < Nk; i++) {
|
||||
std::cout << GridLogMessage << "schurR "<<i<<" "<<S(i,i) << std::endl;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
void schurReorderBlock() {
|
||||
// TODO method stub
|
||||
return;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// template<class Field>
|
||||
// inline void writeFile(const Field &field, const std::string &fname) {
|
||||
// emptyUserRecord record;
|
||||
// ScidacWriter WR(field.Grid()->IsBoss());
|
||||
// WR.open(fname);
|
||||
// WR.writeScidacFieldRecord(field, record, 0); // 0 = Lexico
|
||||
// WR.close();
|
||||
// }
|
||||
|
||||
/**
|
||||
* Implementation of the Krylov-Schur algorithm.
|
||||
*/
|
||||
template<class Field>
|
||||
class KrylovSchur {
|
||||
|
||||
private:
|
||||
|
||||
std::string cname = std::string("KrylovSchur");
|
||||
int MaxIter; // Max iterations
|
||||
RealD Tolerance;
|
||||
RealD ssq;
|
||||
RealD rtol;
|
||||
int Nm; // Number of basis vectors to track (equals MaxIter if no restart)
|
||||
int Nk; // Number of basis vectors to keep every restart (equals -1 if no restart)
|
||||
int Nstop; // Stop after converging Nstop eigenvectors.
|
||||
|
||||
LinearOperatorBase<Field> &Linop;
|
||||
GridBase *Grid;
|
||||
|
||||
RealD approxLambdaMax;
|
||||
RealD beta_k;
|
||||
Field u; // Residual vector perpendicular to Krylov space (u_{k+1} in notes)
|
||||
Eigen::VectorXcd b; // b vector in Schur decomposition (e_{k+1} in Arnoldi).
|
||||
std::vector<Field> basis; // orthonormal Krylov basis
|
||||
Eigen::MatrixXcd Rayleigh; // Rayleigh quotient of size Nbasis (after construction)
|
||||
Eigen::MatrixXcd Qt; // Transpose of basis rotation which projects out high modes.
|
||||
|
||||
Eigen::VectorXcd evals; // evals of Rayleigh quotient
|
||||
std::vector<RealD> ritzEstimates; // corresponding ritz estimates for evals
|
||||
Eigen::MatrixXcd littleEvecs; // Nm x Nm evecs matrix
|
||||
|
||||
RitzFilter ritzFilter; // how to sort evals
|
||||
|
||||
public:
|
||||
bool doEvalCheck = false;
|
||||
|
||||
KrylovSchur(LinearOperatorBase<Field> &_Linop, GridBase *_Grid, RealD _Tolerance, RitzFilter filter = EvalReSmall)
|
||||
: Linop(_Linop), Grid(_Grid), Tolerance(_Tolerance), ritzFilter(filter), u(_Grid), MaxIter(-1), Nm(-1), Nk(-1), Nstop (-1),
|
||||
evals (0), ritzEstimates (), evecs (), ssq (0.0), rtol (0.0), beta_k (0.0), approxLambdaMax (0.0)
|
||||
{
|
||||
u = Zero();
|
||||
};
|
||||
std::vector<Field> evecs; // Vector of evec fields
|
||||
|
||||
|
||||
/* Getters */
|
||||
int getNk() { return Nk; }
|
||||
Eigen::MatrixXcd getRayleighQuotient() { return Rayleigh; }
|
||||
Field getU() { return u; }
|
||||
std::vector<Field> getBasis() { return basis; }
|
||||
Eigen::VectorXcd getEvals() { return evals; }
|
||||
std::vector<RealD> getRitzEstimates() { return ritzEstimates; }
|
||||
std::vector<Field> getEvecs() { return evecs; }
|
||||
|
||||
/**
|
||||
* Runs the non-harmonic Krylov-Schur loop.
|
||||
* - Runs an Arnoldi step to generate the Rayleigh quotient and Krylov basis.
|
||||
* - Schur decompose the Rayleigh quotient.
|
||||
* - Permutes the Rayleigh quotient according to the eigenvalues.
|
||||
* - Truncate the Krylov-Schur expansion.
|
||||
*/
|
||||
void operator()(const Field& v0, int _maxIter, int _Nm, int _Nk, int _Nstop, bool doubleOrthog = true) {
|
||||
|
||||
MaxIter = _maxIter;
|
||||
Nm = _Nm; Nk = _Nk;
|
||||
Nstop = _Nstop;
|
||||
|
||||
ssq = norm2(v0);
|
||||
RealD approxLambdaMax = approxMaxEval(v0);
|
||||
rtol = Tolerance * approxLambdaMax;
|
||||
std::cout << GridLogMessage << "Approximate max eigenvalue: " << approxLambdaMax << std::endl;
|
||||
|
||||
b = Eigen::VectorXcd::Zero(Nm); // start as e_{k+1}
|
||||
b(Nm-1) = 1.0;
|
||||
|
||||
int start = 0;
|
||||
Field startVec = v0;
|
||||
littleEvecs = Eigen::MatrixXcd::Zero(Nm, Nm);
|
||||
for (int i = 0; i < MaxIter; i++) {
|
||||
std::cout << GridLogMessage << "Restart Iteration " << i << std::endl;
|
||||
|
||||
// Perform Arnoldi steps to compute Krylov basis and Rayleigh quotient (Hess)
|
||||
arnoldiIteration(startVec, Nm, start, doubleOrthog);
|
||||
startVec = u;
|
||||
start = Nk;
|
||||
|
||||
std::cout << GridLogDebug << "b after Arnoldi " << b << std::endl;
|
||||
|
||||
// --- Restart: Schur-decompose Rayleigh, reorder by ritzFilter, rotate
|
||||
// the basis into the Schur vectors, and truncate to the leading Nk.
|
||||
ComplexSchurDecomposition schur (Rayleigh, false, ritzFilter);
|
||||
std::cout << GridLogDebug << "Schur decomp holds? " << schur.checkDecomposition() << std::endl;
|
||||
|
||||
// Rearrange Schur matrix so wanted evals are on top left (like MATLAB's ordschur)
|
||||
std::cout << GridLogMessage << "Reordering Schur eigenvalues" << std::endl;
|
||||
schur.schurReorder(Nk);
|
||||
std::cout << GridLogMessage << "Schur eigenvalues reordered." << std::endl;
|
||||
|
||||
Eigen::MatrixXcd Q = schur.getMatrixQ();
|
||||
Qt = Q.adjoint(); // TODO should Q be real?
|
||||
|
||||
std::cout << GridLogMessage << "*** ROTATING TO SCHUR BASIS *** " << std::endl;
|
||||
|
||||
// Rotate Krylov basis, b vector, redefine Rayleigh quotient and evecs, and truncate.
|
||||
Rayleigh = schur.getMatrixS();
|
||||
b = Q * b; // b^\dag = b^\dag * Q^\dag <==> b = Q*b
|
||||
|
||||
std::vector<Field> basis2;
|
||||
constructUR(basis2, basis, Qt, Nm,Nk);
|
||||
|
||||
std::cout << GridLogMessage << "*** TRUNCATING FOR RESTART *** " << std::endl;
|
||||
std::cout << GridLogDebug << "Rayleigh before truncation: " << std::endl << Rayleigh << std::endl;
|
||||
|
||||
Eigen::MatrixXcd RayTmp = Rayleigh(Eigen::seqN(0, Nk), Eigen::seqN(0, Nk));
|
||||
Rayleigh = RayTmp;
|
||||
|
||||
basis = std::vector<Field> (basis2.begin(), basis2.begin() + Nk);
|
||||
|
||||
b = b.head(Nk).eval();
|
||||
|
||||
std::cout << GridLogDebug << "Rayleigh after truncation: " << std::endl << Rayleigh << std::endl;
|
||||
|
||||
checkKSDecomposition();
|
||||
|
||||
// Compute eigensystem of Rayleigh. Note the eigenvectors correspond to the sorted eigenvalues.
|
||||
computeEigensystem(Rayleigh);
|
||||
std::cout << GridLogMessage << "Eigenvalues (first Nk sorted): " << std::endl << evals << std::endl;
|
||||
|
||||
if (checkConvergedAndReport(i)) return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the harmonic (shifted) Krylov-Schur loop: extracts Ritz values of a
|
||||
* shift-augmented Rayleigh quotient so that eigenvalues near `*_shift` are
|
||||
* reordered to the top instead of the extremal ones.
|
||||
*/
|
||||
void operator()(const Field& v0, int _maxIter, int _Nm, int _Nk, int _Nstop, RealD *_shift, bool doubleOrthog = true) {
|
||||
|
||||
assert(_shift && "harmonic KrylovSchur: shift must be non-null");
|
||||
RealD shiftVal = *_shift;
|
||||
|
||||
MaxIter = _maxIter;
|
||||
Nm = _Nm; Nk = _Nk;
|
||||
Nstop = _Nstop;
|
||||
|
||||
ssq = norm2(v0);
|
||||
RealD approxLambdaMax = approxMaxEval(v0);
|
||||
rtol = Tolerance * approxLambdaMax;
|
||||
std::cout << GridLogMessage << "Approximate max eigenvalue: " << approxLambdaMax << std::endl;
|
||||
|
||||
b = Eigen::VectorXcd::Zero(Nm); // start as e_{k+1}
|
||||
b(Nm-1) = 1.0;
|
||||
|
||||
int start = 0;
|
||||
Field startVec = v0;
|
||||
littleEvecs = Eigen::MatrixXcd::Zero(Nm, Nm);
|
||||
for (int i = 0; i < MaxIter; i++) {
|
||||
std::cout << GridLogMessage << "Restart Iteration " << i << std::endl;
|
||||
|
||||
// Perform Arnoldi steps to compute Krylov basis and Rayleigh quotient (Hess)
|
||||
arnoldiIteration(startVec, Nm, start, doubleOrthog);
|
||||
startVec = u;
|
||||
start = Nk;
|
||||
|
||||
std::cout << GridLogDebug << "b after Arnoldi " << b << std::endl;
|
||||
|
||||
// --- Harmonic restart: Schur-decompose the shift-augmented Rayleigh
|
||||
// quotient so Ritz values close to shiftVal are reordered to the
|
||||
// top, then rotate and truncate as in the non-harmonic case.
|
||||
Eigen::MatrixXcd temp = Rayleigh;
|
||||
for (int m=0;m<Nm;m++) temp(m,m) -= shiftVal;
|
||||
Eigen::MatrixXcd RayleighS = temp.inverse(); // (B-tI)^-1
|
||||
Eigen::MatrixXcd temp2 = RayleighS.adjoint(); //(B-tI)^-1*
|
||||
Eigen::VectorXcd g = temp2*b; //g = (B-tI)^-1* * b
|
||||
Eigen::MatrixXcd Btilde = Rayleigh + g*(b.adjoint());
|
||||
|
||||
Field utilde(Grid);
|
||||
utilde = u;
|
||||
for (int j = 0; j<Nm; j++){
|
||||
utilde -= basis[j]*g(j);
|
||||
}
|
||||
|
||||
ComplexSchurDecomposition schurS (Btilde, false, ritzFilter);
|
||||
std::cout << GridLogMessage << "Shifted Schur eigenvalues shift = "<<shiftVal << std::endl;
|
||||
schurS.schurReorder(Nk);
|
||||
|
||||
Eigen::MatrixXcd Q_s = schurS.getMatrixQ();
|
||||
Eigen::MatrixXcd Qt_s = Q_s.adjoint(); // TODO should Q be real?
|
||||
|
||||
Btilde=schurS.getMatrixS();
|
||||
Eigen::VectorXcd b_s = Q_s*b; // Q is Qt in SlepC, b_s=bhat
|
||||
|
||||
std::vector<Field> basis2_s;
|
||||
constructUR(basis2_s, basis, Qt_s, Nm,Nk);
|
||||
|
||||
Eigen::MatrixXcd RayTmp_s = Btilde(Eigen::seqN(0, Nk), Eigen::seqN(0, Nk));
|
||||
Btilde = RayTmp_s;
|
||||
|
||||
basis2_s = std::vector<Field> (basis2_s.begin(), basis2_s.begin() + Nk);
|
||||
|
||||
b_s = b_s.head(Nk).eval();
|
||||
|
||||
Eigen::VectorXcd ghat = -Q_s * g;
|
||||
ghat = ghat.head(Nk).eval();
|
||||
|
||||
Field uhat(Grid);
|
||||
uhat = utilde;
|
||||
for (int j = 0; j<Nk; j++){
|
||||
uhat -= basis2_s[j]*ghat(j);
|
||||
}
|
||||
|
||||
RealD gamma = std::sqrt(norm2(uhat));
|
||||
uhat *= 1.0/gamma;
|
||||
std::cout << GridLogMessage << " gamma "<<gamma << std::endl;
|
||||
|
||||
Btilde += ghat*(b_s.adjoint());
|
||||
b_s *=gamma;
|
||||
|
||||
Rayleigh = Btilde;
|
||||
basis= basis2_s;
|
||||
b = b_s;
|
||||
beta_k = gamma;
|
||||
u= uhat;
|
||||
|
||||
checkKSDecomposition();
|
||||
computeEigensystem(Rayleigh);
|
||||
std::cout << GridLogMessage << "Eigenvalues (first Nk sorted): " << std::endl << evals << std::endl;
|
||||
|
||||
if (checkConvergedAndReport(i)) return;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* Shared post-restart convergence check. On convergence (or the final
|
||||
* iteration) reports eigenvalues and optionally the explicit residual
|
||||
* check. Returns true if operator() should return.
|
||||
*/
|
||||
bool checkConvergedAndReport(int i) {
|
||||
int Nconv = converged();
|
||||
std::cout << GridLogMessage << "Number of evecs converged: " << Nconv << std::endl;
|
||||
if (Nconv >= Nstop || i == MaxIter - 1) {
|
||||
std::cout << GridLogMessage << "Converged with " << Nconv << " / " << Nstop << " eigenvectors on iteration "
|
||||
<< i << "." << std::endl;
|
||||
std::cout << GridLogMessage << "Eigenvalues: " << std::endl << evals << std::endl;
|
||||
|
||||
if (doEvalCheck) {
|
||||
Field w(Grid);
|
||||
for (int k = 0; k < (int)evecs.size(); k++) {
|
||||
Linop.Op(evecs[k], w);
|
||||
ComplexD eval_est = toStdCmplx(innerProduct(evecs[k], w));
|
||||
w -= eval_est * evecs[k];
|
||||
RealD res = std::sqrt(norm2(w));
|
||||
std::cout << GridLogMessage << "KrylovSchur: evec[" << k << "]"
|
||||
<< " eval_reported = " << evals[k]
|
||||
<< " eval_est = " << eval_est
|
||||
<< " || A v - eval_est * v || = " << res << std::endl;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
/**
|
||||
* Constructs the Arnoldi basis for the Krylov space K_n(D, src). (TODO make private)
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* v0 : Field&
|
||||
* Source to generate Krylov basis.
|
||||
* Nm : int
|
||||
* Final size of the basis desired. If the basis becomes complete before a basis of size Nm is constructed
|
||||
* (determined by relative tolerance Tolerance), stops iteration there.
|
||||
* doubleOrthog : bool (default = false)
|
||||
* Whether to double orthogonalize the basis (for numerical cancellations) or not.
|
||||
* start : int (default = 0)
|
||||
* If non-zero, assumes part of the Arnoldi basis has already been constructed.
|
||||
*/
|
||||
void arnoldiIteration(const Field& v0, int Nm, int start = 0, bool doubleOrthog = true)
|
||||
{
|
||||
|
||||
ComplexD coeff;
|
||||
Field w (Grid); // A acting on last Krylov vector.
|
||||
|
||||
// basis.reserve(Nm);
|
||||
// for (int i = start; i < Nm; i++) {
|
||||
// basis.emplace_back(Grid);
|
||||
// }
|
||||
// basis.assign(Nm, Field(Grid));
|
||||
// basis.resize(Nm);
|
||||
// for (int i = start; i < Nm; i++) {
|
||||
// basis[i] = Field(Grid);
|
||||
// }
|
||||
|
||||
if (start == 0) { // initialize everything that we need.
|
||||
RealD v0Norm = 1 / std::sqrt(ssq);
|
||||
basis.push_back(v0Norm * v0); // normalized source
|
||||
// basis[0] = v0Norm * v0; // normalized source
|
||||
|
||||
Rayleigh = Eigen::MatrixXcd::Zero(Nm, Nm);
|
||||
u = Zero();
|
||||
} else {
|
||||
// assert( start == basis.size() ); // should be starting at the end of basis (start = Nk)
|
||||
std::cout << GridLogMessage << "Resetting Rayleigh and b" << std::endl;
|
||||
Eigen::MatrixXcd RayleighCp = Rayleigh;
|
||||
Rayleigh = Eigen::MatrixXcd::Zero(Nm, Nm);
|
||||
Rayleigh(Eigen::seqN(0, Nk), Eigen::seqN(0, Nk)) = RayleighCp;
|
||||
|
||||
// append b^\dag to Rayleigh, add u to basis
|
||||
Rayleigh(Nk, Eigen::seqN(0, Nk)) = b.adjoint();
|
||||
basis.push_back(u);
|
||||
// basis[start] = u; // TODO make sure this is correct
|
||||
b = Eigen::VectorXcd::Zero(Nm);
|
||||
}
|
||||
|
||||
// Construct next Arnoldi vector by normalizing w_i = Dv_i - \sum_j v_j h_{ji}
|
||||
for (int i = start; i < Nm; i++) {
|
||||
Linop.Op(basis.back(), w);
|
||||
// Linop.Op(basis[i], w);
|
||||
for (int j = 0; j < basis.size(); j++) {
|
||||
coeff = innerProduct(basis[j], w); // coeff = h_{ij}. Note that since {vi} is ONB it's OK to subtract it off after.
|
||||
Rayleigh(j, i) = toStdCmplx(coeff);
|
||||
w -= coeff * basis[j];
|
||||
}
|
||||
|
||||
if (doubleOrthog) {
|
||||
std::cout << GridLogDebug << "Double orthogonalizing." << std::endl;
|
||||
for (int j = 0; j < basis.size(); j++) {
|
||||
coeff = innerProduct(basis[j], w); // see if there is any residual component in basis[j] direction
|
||||
Rayleigh(j, i) += toStdCmplx(coeff); // if coeff is non-zero, adjust Rayleigh
|
||||
w -= coeff * basis[j];
|
||||
}
|
||||
}
|
||||
|
||||
// add w_i to the pile
|
||||
if (i < Nm - 1) {
|
||||
coeff = std::sqrt(norm2(w));
|
||||
Rayleigh(i+1, i) = toStdCmplx(coeff);
|
||||
basis.push_back(
|
||||
(1.0/coeff) * w
|
||||
);
|
||||
// basis[i+1] = (1.0/coeff) * w;
|
||||
}
|
||||
|
||||
// after iterations, update u and beta_k = ||u|| before norm
|
||||
u = w; // make sure u is normalized
|
||||
beta_k = std::sqrt(norm2(u)); // beta_k = ||f_k|| determines convergence.
|
||||
u = (1/beta_k) * u;
|
||||
}
|
||||
|
||||
b(Nm - 1) = beta_k;
|
||||
|
||||
// std::cout << GridLogMessage << "|f|^2 after Arnoldi step = " << norm2(f) << std::endl;
|
||||
std::cout << GridLogMessage << "beta_k = |u| (before norm) after Arnoldi step = " << beta_k << std::endl;
|
||||
std::cout << GridLogDebug << "Computed Rayleigh quotient = " << std::endl << Rayleigh << std::endl;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximates the eigensystem of the linear operator by computing the eigensystem of
|
||||
* the Rayleigh quotient. Assumes that the Rayleigh quotient has already been constructed (by
|
||||
* calling the operator() function).
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* Eigen::MatrixXcd& S
|
||||
* Schur matrix (upper triangular) similar to original Rayleigh quotient.
|
||||
*/
|
||||
void computeEigensystem(Eigen::MatrixXcd& S)
|
||||
{
|
||||
std::cout << GridLogMessage << "Computing eigenvalues." << std::endl;
|
||||
|
||||
evecs.clear();
|
||||
|
||||
Eigen::ComplexEigenSolver<Eigen::MatrixXcd> es;
|
||||
es.compute(S);
|
||||
|
||||
// Sort eigenvalues/evecs to match the schurReorder ordering.
|
||||
int n = es.eigenvalues().size();
|
||||
ComplexComparator cComp(ritzFilter);
|
||||
std::vector<int> idx(n);
|
||||
std::iota(idx.begin(), idx.end(), 0);
|
||||
std::sort(idx.begin(), idx.end(), [&](int a, int b){
|
||||
return cComp(toStdCmplx(es.eigenvalues()(a)), toStdCmplx(es.eigenvalues()(b)));
|
||||
});
|
||||
|
||||
evals.resize(n);
|
||||
littleEvecs.resize(n, n);
|
||||
for (int k = 0; k < n; k++) {
|
||||
evals(k) = es.eigenvalues()(idx[k]);
|
||||
littleEvecs.col(k) = es.eigenvectors().col(idx[k]);
|
||||
}
|
||||
|
||||
// Convert evecs to lattice fields
|
||||
for (int k = 0; k < n; k++) {
|
||||
Eigen::VectorXcd vec = littleEvecs.col(k);
|
||||
Field tmp (basis[0].Grid());
|
||||
tmp = Zero();
|
||||
for (int j = 0; j < (int)basis.size(); j++) {
|
||||
tmp = tmp + vec[j] * basis[j];
|
||||
}
|
||||
evecs.push_back(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximates the maximum eigenvalue of Linop.Op to normalize the residual and test for convergence.
|
||||
*
|
||||
* TODO implement in parent class eventually
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* Field& v0
|
||||
* Source field to start with. Must have non-zero norm.
|
||||
* int MAX_ITER (default = 50)
|
||||
* Maximum number of iterations for power approximation.
|
||||
*
|
||||
* Returns
|
||||
* -------
|
||||
* RealD lamApprox
|
||||
* Approximation of largest eigenvalue.
|
||||
*/
|
||||
RealD approxMaxEval(const Field& v0, int MAX_ITER = 50) {
|
||||
assert (norm2(v0) > 1e-8); // must have relatively large source norm to start
|
||||
RealD lamApprox = 0.0;
|
||||
RealD denom = 1.0; RealD num = 1.0;
|
||||
Field v0cp (Grid); Field tmp (Grid);
|
||||
v0cp = v0;
|
||||
denom = std::sqrt(norm2(v0cp));
|
||||
for (int i = 0; i < MAX_ITER; i++) {
|
||||
Linop.Op(v0cp, tmp); // CAREFUL: do not do Op(tmp, tmp)
|
||||
v0cp = tmp;
|
||||
num = std::sqrt(norm2(v0cp)); // num = |A^{n+1} v0|
|
||||
lamApprox = num / denom; // lam = |A^{n+1} v0| / |A^n v0|
|
||||
std::cout << GridLogDebug << "Approx for max eval: " << lamApprox << std::endl;
|
||||
denom = num; // denom = |A^{n} v0|
|
||||
}
|
||||
return lamApprox;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the number of Krylov-Schur eigenvectors that have converged. An eigenvector s is considered converged
|
||||
* for a tolerance epsilon if
|
||||
* r(s) := |\beta e_m^T s| < epsilon
|
||||
* where beta is the norm of f_{m+1}.
|
||||
*
|
||||
* TODO implement in parent class eventually
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
*
|
||||
* Returns
|
||||
* -------
|
||||
* int : Number of converged eigenvectors.
|
||||
*/
|
||||
int converged() {
|
||||
int Nconv = 0;
|
||||
int _Nm = evecs.size();
|
||||
std::cout << GridLogDebug << "b: " << b << std::endl;
|
||||
Field tmp (Grid); Field fullEvec (Grid);
|
||||
ritzEstimates.clear();
|
||||
// ritzEstimates.resize(_Nm);
|
||||
for (int k = 0; k < _Nm; k++) {
|
||||
Eigen::VectorXcd evec_k = littleEvecs.col(k);
|
||||
RealD ritzEstimate = std::abs(b.dot(evec_k)); // b^\dagger s
|
||||
ritzEstimates.push_back(ritzEstimate);
|
||||
std::cout << GridLogMessage << "Ritz estimate for evec " << k << " = " << ritzEstimate << std::endl;
|
||||
if (ritzEstimate < rtol) {
|
||||
Nconv++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Check that Ritz estimate is explicitly || D (Uy) - lambda (Uy) ||
|
||||
// checkRitzEstimate();
|
||||
return Nconv;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the Krylov-Schur decomposition DU = UR + f b^\dag with the last-computed
|
||||
* U, R, f, and b.
|
||||
*/
|
||||
bool checkKSDecomposition(RealD tol = 1e-8) {
|
||||
|
||||
std::cout << GridLogMessage << "*** CHECKING KRYLOV-SCHUR DECOMPOSITION *** " << std::endl;
|
||||
|
||||
int k = basis.size(); // number of basis vectors, also the size of Rayleigh.
|
||||
|
||||
// rotate basis by Rayleigh to construct UR
|
||||
// std::vector<Field> rotated;
|
||||
|
||||
// std::cout << GridLogDebug << "Rayleigh in KSDecomposition: " << std::endl << Rayleigh << std::endl;
|
||||
|
||||
std::vector<Field> rotated = basis;
|
||||
constructUR(rotated, basis, Rayleigh, k,k); // manually rotate
|
||||
// Eigen::MatrixXcd Rt = Rayleigh.adjoint();
|
||||
// basisRotate(rotated, Rt, 0, k, 0, k, k); // UR
|
||||
|
||||
// TODO: make a new function that I'm positive does what this is doing
|
||||
// just take the basis U = (u1 u2 ... uNm) and form the linear combination UR from R
|
||||
|
||||
// For each i, form D u(i) and subtract off (US - u b^\dag)(i)
|
||||
RealD delta = 0.0; RealD deltaSum = 0;
|
||||
Field tmp (Grid); tmp = Zero();
|
||||
for (int i = 0; i < k; i++) {
|
||||
Linop.Op(basis[i], tmp); // tmp = D u(i)
|
||||
delta = norm2(tmp - rotated[i] - u * std::conj(b(i)));
|
||||
delta = delta / norm2(tmp); // relative tolerance
|
||||
deltaSum += delta;
|
||||
|
||||
// std::cout << GridLogDebug << "Iteration " << i << std::endl;
|
||||
// std::cout << GridLogDebug << "Du = " << norm2(tmp) << std::endl;
|
||||
// std::cout << GridLogDebug << "rotated = " << norm2(rotated[i]) << std::endl;
|
||||
// std::cout << GridLogDebug << "b[i] = " << b(i) << std::endl;
|
||||
std::cout << GridLogMessage << "Deviation in decomp, column " << i << ": " << delta << std::endl;
|
||||
}
|
||||
std::cout << GridLogMessage << "Squared sum of relative deviations in decomposition: " << deltaSum << std::endl;
|
||||
|
||||
// std::cout << "[DEBUG] testing basis rotate" << std::endl;
|
||||
// std::vector<Field> rotated2;
|
||||
// constructUR(rotated2, basis, Rayleigh, k);
|
||||
// for (int i = 0; i < k; i++) {
|
||||
// std::cout << "rotated[i] - UR[i] = " << norm2(rotated[i] - rotated2[i]) << std::endl;
|
||||
// }
|
||||
|
||||
return deltaSum < tol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the Ritz vector s was rotated correctly by explicitly recomputing the
|
||||
* eigenvectors of the rotated Rayleigh quotient.
|
||||
*/
|
||||
bool checkRitzRotation(RealD tol = 1e-8) {
|
||||
std::cout << GridLogMessage << "*** CHECKING RITZ VECTOR ROTATION *** " << std::endl;
|
||||
|
||||
Eigen::ComplexEigenSolver<Eigen::MatrixXcd> es;
|
||||
es.compute(Rayleigh);
|
||||
Eigen::MatrixXcd littleEvecs2 = es.eigenvectors();
|
||||
RealD dLittle = (littleEvecs2 - littleEvecs).norm() / littleEvecs.norm();
|
||||
std::cout << GridLogMessage << "|littleEvecs2 - littleEvecs| / |littleEvecs| = " << dLittle << std::endl;
|
||||
|
||||
std::cout << GridLogMessage << "Forming full eigenvectors" << std::endl;
|
||||
RealD delta = 0.0; RealD deltaSum = 0;
|
||||
for (int k = 0; k < evals.size(); k++) {
|
||||
Eigen::VectorXcd vec = littleEvecs.col(k);
|
||||
Field tmpEvec (Grid);
|
||||
tmpEvec = Zero();
|
||||
for (int j = 0; j < basis.size(); j++) {
|
||||
tmpEvec = tmpEvec + vec[j] * basis[j];
|
||||
}
|
||||
delta = norm2(tmpEvec - evecs[k]) / norm2(evecs[k]);
|
||||
std::cout << GridLogMessage << "Deviation in evec " << k << ": " << delta << std::endl;
|
||||
deltaSum += delta;
|
||||
}
|
||||
return deltaSum < tol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the Ritz estimate R(s) is indeed the deviation of a Ritz eigenvector from being a true eigenvector.
|
||||
*/
|
||||
void checkRitzEstimate(RealD tol = 1e-8) {
|
||||
std::cout << GridLogMessage << "*** CHECKING RITZ ESTIMATE *** " << std::endl;
|
||||
|
||||
// The issue was that the Eigen::eigensolver occasionally returned the complex conjugate pairs in the wrong
|
||||
// order compared to the diagonal, which is how I was reading them out. When this happened, the Ritz estimate would
|
||||
// be wrong. So, just need to be more careful and actually read out the eigenvalues.
|
||||
|
||||
Field tmp (Grid);
|
||||
// std::cout << "n evecs: " << evecs.size() << std::endl;
|
||||
for (int k = 0; k < evecs.size(); k++) {
|
||||
tmp = Zero();
|
||||
Linop.Op(evecs[k], tmp); // D evec
|
||||
RealD ritz = std::sqrt(norm2(tmp - evals[k] * evecs[k]));
|
||||
std::cout << "Ritz estimate " << k << " = " << ritz << std::endl;
|
||||
|
||||
// Checking little Ritz estimate
|
||||
// Eigen::VectorXcd littleEvec = littleEvecs.col(k);
|
||||
// Eigen::VectorXcd dev = Rayleigh * littleEvec - evals[k] * littleEvec;
|
||||
// std::cout << GridLogMessage << "Little Ritz estimate = " << dev.norm() << std::endl;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a vector of fields U (equivalently, a LxN matrix, where L is the number of degrees of
|
||||
* freedom on the lattice field) and an NxN matrix R, forms the product UR.
|
||||
* Only the first N2 output columns are computed; columns [N2, N) are Zero.
|
||||
*
|
||||
* Implemented with the accelerator basisRotate kernel, which computes
|
||||
* basis[j] <- sum_k Qt(j,k) basis[k] in place, so we copy U into UR and
|
||||
* pass R^T. The coefficients are staged as ComplexD (thrust::complex on
|
||||
* GPU builds) since std::complex has no device arithmetic with Grid tensors.
|
||||
*/
|
||||
void constructUR(std::vector<Field>& UR, std::vector<Field> &U, Eigen::MatrixXcd& R, int N, int N2) {
|
||||
KSCoeffMat Rt(N);
|
||||
for (int i = 0; i < N; i++)
|
||||
for (int j = 0; j < N; j++)
|
||||
Rt(i, j) = ComplexD(R(j, i).real(), R(j, i).imag());
|
||||
|
||||
UR = U;
|
||||
basisRotate(UR, Rt, 0, N2, 0, N, N);
|
||||
for (int i = N2; i < N; i++) UR[i] = Zero();
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as constructUR but for the product order RU.
|
||||
*/
|
||||
void constructRU(std::vector<Field>& RU, std::vector<Field> &U, Eigen::MatrixXcd& R, int N) {
|
||||
Field tmp (Grid);
|
||||
RU.clear();
|
||||
// RU.resize(N);
|
||||
for (int i = 0; i < N; i++) {
|
||||
tmp = Zero();
|
||||
for (int j = 0; j < N; j++) {
|
||||
tmp = tmp + R(i, j) * U[j];
|
||||
}
|
||||
RU.push_back(tmp);
|
||||
// RU[i] = tmp;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// void writeEvec(Field& in, std::string const fname){
|
||||
// #ifdef HAVE_LIME
|
||||
// // Ref: https://github.com/paboyle/Grid/blob/feature/scidac-wp1/tests/debug/Test_general_coarse_hdcg_phys48.cc#L111
|
||||
// std::cout << GridLogMessage << "Writing evec to: " << fname << std::endl;
|
||||
// Grid::emptyUserRecord record;
|
||||
// Grid::ScidacWriter WR(in.Grid()->IsBoss());
|
||||
// WR.open(fname);
|
||||
// WR.writeScidacFieldRecord(in,record,0); // Lexico
|
||||
// WR.close();
|
||||
// #endif
|
||||
// // What is the appropriate way to throw error?
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Writes the eigensystem of a Krylov Schur object to a directory.
|
||||
// *
|
||||
// * Parameters
|
||||
// * ----------
|
||||
// * std::string path
|
||||
// * Directory to write to.
|
||||
// */
|
||||
// void writeEigensystem(std::string outDir) {
|
||||
// std::cout << GridLogMessage << "Writing output to directory: " << outDir << std::endl;
|
||||
// // TODO write a scidac density file so that we can easily integrate with visualization toolkit
|
||||
// std::string evalPath = outDir + "/evals.txt";
|
||||
// std::ofstream fEval;
|
||||
// fEval.open(evalPath);
|
||||
// for (int i = 0; i < Nk; i++) {
|
||||
// // write Eigenvalues
|
||||
// fEval << i << " " << evals(i);
|
||||
// if (i < Nk - 1) { fEval << "\n"; }
|
||||
// }
|
||||
// fEval.close();
|
||||
|
||||
// for (int i = 0; i < Nk; i++) {
|
||||
// std::string fName = outDir + "/evec" + std::to_string(i);
|
||||
// // writeFile(evecs[i], fName); // using method from Grid/HMC/ComputeWilsonFlow.cc
|
||||
// // writeEvec(evecs[i], fName);
|
||||
// }
|
||||
|
||||
// }
|
||||
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
#endif
|
||||
@@ -0,0 +1,276 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./Grid/algorithms/iterative/LanczosBidiagonalization.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Chulwoo Jung <chulwoo@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_LANCZOS_BIDIAGONALIZATION_H
|
||||
#define GRID_LANCZOS_BIDIAGONALIZATION_H
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
/**
|
||||
* Lanczos Bidiagonalization (Golub-Kahan)
|
||||
*
|
||||
* For a linear operator A with adjoint A^dag, constructs the bidiagonal
|
||||
* decomposition:
|
||||
*
|
||||
* A V_m = U_m B_m
|
||||
* A^dag U_m = V_m B_m^T + beta_{m+1} v_{m+1} e_m^T
|
||||
*
|
||||
* where:
|
||||
* V_m = [v_1, ..., v_m] right Lanczos vectors (orthonormal)
|
||||
* U_m = [u_1, ..., u_m] left Lanczos vectors (orthonormal)
|
||||
* B_m is upper bidiagonal with diag(alpha_1,...,alpha_m) and
|
||||
* superdiag(beta_2,...,beta_m)
|
||||
*
|
||||
* The singular values of A are approximated by those of B_m.
|
||||
* The singular values of B_m are the square roots of the eigenvalues of
|
||||
* the symmetric tridiagonal matrix B_m^T B_m.
|
||||
*
|
||||
* Usage:
|
||||
* LanczosBidiagonalization<Field> lb(Linop, grid);
|
||||
* lb.run(src, Nm, tol);
|
||||
* // Access results via getters.
|
||||
*/
|
||||
template <class Field>
|
||||
class LanczosBidiagonalization {
|
||||
|
||||
public:
|
||||
LinearOperatorBase<Field> &Linop;
|
||||
GridBase *Grid;
|
||||
|
||||
int Nm; // number of Lanczos steps taken
|
||||
RealD Tolerance; // convergence threshold on beta_{k+1} / alpha_k
|
||||
|
||||
std::vector<Field> V; // right Lanczos vectors v_1 ... v_m
|
||||
std::vector<Field> U; // left Lanczos vectors u_1 ... u_m
|
||||
std::vector<RealD> alpha; // diagonal of bidiagonal matrix
|
||||
std::vector<RealD> beta; // super-diagonal (beta[k] couples u_k and v_{k+1})
|
||||
|
||||
// SVD of the bidiagonal matrix (filled after computeSVD())
|
||||
Eigen::VectorXd singularValues;
|
||||
Eigen::MatrixXd leftSVecs; // columns are left singular vectors of B
|
||||
Eigen::MatrixXd rightSVecs; // columns are right singular vectors of B
|
||||
|
||||
public:
|
||||
|
||||
LanczosBidiagonalization(LinearOperatorBase<Field> &_Linop, GridBase *_Grid,
|
||||
RealD _tol = 1.0e-8)
|
||||
: Linop(_Linop), Grid(_Grid), Tolerance(_tol), Nm(0)
|
||||
{}
|
||||
|
||||
/**
|
||||
* Run the Golub-Kahan Lanczos bidiagonalization.
|
||||
*
|
||||
* Parameters
|
||||
* ----------
|
||||
* src : starting vector (need not be normalised)
|
||||
* Nmax : maximum number of Lanczos steps
|
||||
* reorth : if true, full reorthogonalisation of both V and U bases
|
||||
*/
|
||||
void run(const Field &src, int Nmax, bool reorth = true)
|
||||
{
|
||||
assert(norm2(src) > 0.0);
|
||||
|
||||
V.clear(); U.clear();
|
||||
alpha.clear(); beta.clear();
|
||||
Nm = 0;
|
||||
|
||||
Field p(Grid), r(Grid);
|
||||
|
||||
// --- initialise: v_1 = src / ||src|| ---
|
||||
Field v(Grid);
|
||||
v = src;
|
||||
RealD nrm = std::sqrt(norm2(v));
|
||||
v = (1.0 / nrm) * v;
|
||||
V.push_back(v);
|
||||
|
||||
for (int k = 0; k < Nmax; ++k) {
|
||||
|
||||
// p = A v_k
|
||||
Linop.Op(V[k], p);
|
||||
|
||||
// p = p - beta_k * u_{k-1} (remove previous left vector)
|
||||
if (k > 0) {
|
||||
p = p - beta[k-1] * U[k-1];
|
||||
}
|
||||
|
||||
// alpha_k = ||p||
|
||||
RealD ak = std::sqrt(norm2(p));
|
||||
if (ak < 1.0e-14) {
|
||||
std::cout << GridLogMessage
|
||||
<< "LanczosBidiagonalization: lucky breakdown at step "
|
||||
<< k << " (alpha = " << ak << ")" << std::endl;
|
||||
break;
|
||||
}
|
||||
alpha.push_back(ak);
|
||||
|
||||
// u_k = p / alpha_k
|
||||
Field u(Grid);
|
||||
u = (1.0 / ak) * p;
|
||||
|
||||
// full reorthogonalisation of u against previous U
|
||||
if (reorth) {
|
||||
for (int j = 0; j < (int)U.size(); ++j) {
|
||||
ComplexD ip = innerProduct(U[j], u);
|
||||
u = u - ip * U[j];
|
||||
}
|
||||
RealD unrm = std::sqrt(norm2(u));
|
||||
if (unrm > 1.0e-14) u = (1.0 / unrm) * u;
|
||||
}
|
||||
U.push_back(u);
|
||||
|
||||
// r = A^dag u_k - alpha_k * v_k
|
||||
Linop.AdjOp(U[k], r);
|
||||
r = r - ak * V[k];
|
||||
|
||||
// full reorthogonalisation of r against previous V
|
||||
if (reorth) {
|
||||
for (int j = 0; j < (int)V.size(); ++j) {
|
||||
ComplexD ip = innerProduct(V[j], r);
|
||||
r = r - ip * V[j];
|
||||
}
|
||||
}
|
||||
|
||||
// beta_{k+1} = ||r||
|
||||
RealD bk = std::sqrt(norm2(r));
|
||||
beta.push_back(bk);
|
||||
|
||||
Nm = k + 1;
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "LanczosBidiagonalization step " << k
|
||||
<< " alpha = " << ak
|
||||
<< " beta = " << bk << std::endl;
|
||||
|
||||
// convergence: residual beta / alpha small enough
|
||||
if (bk / ak < Tolerance) {
|
||||
std::cout << GridLogMessage
|
||||
<< "LanczosBidiagonalization converged at step " << k
|
||||
<< " (beta/alpha = " << bk / ak << ")" << std::endl;
|
||||
break;
|
||||
}
|
||||
|
||||
if (k == Nmax - 1) break; // no v_{k+2} needed after last step
|
||||
|
||||
// v_{k+1} = r / beta_{k+1}
|
||||
Field vnext(Grid);
|
||||
vnext = (1.0 / bk) * r;
|
||||
V.push_back(vnext);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the SVD of the bidiagonal matrix B using Eigen.
|
||||
* Singular values are stored in descending order.
|
||||
*/
|
||||
void computeSVD()
|
||||
{
|
||||
int m = Nm;
|
||||
Eigen::MatrixXd B = Eigen::MatrixXd::Zero(m, m);
|
||||
|
||||
for (int k = 0; k < m; ++k) {
|
||||
B(k, k) = alpha[k];
|
||||
if (k + 1 < m && k < (int)beta.size())
|
||||
B(k, k+1) = beta[k];
|
||||
}
|
||||
|
||||
Eigen::JacobiSVD<Eigen::MatrixXd> svd(B,
|
||||
Eigen::ComputeThinU | Eigen::ComputeThinV);
|
||||
|
||||
singularValues = svd.singularValues(); // already sorted descending
|
||||
leftSVecs = svd.matrixU();
|
||||
rightSVecs = svd.matrixV();
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "LanczosBidiagonalization: singular values of B_" << m
|
||||
<< std::endl;
|
||||
for (int k = 0; k < m; ++k)
|
||||
std::cout << GridLogMessage << " sigma[" << k << "] = "
|
||||
<< singularValues(k) << std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the k-th approximate left singular vector of A in the full
|
||||
* lattice space. computeSVD() must have been called first.
|
||||
*/
|
||||
Field leftSingularVector(int k)
|
||||
{
|
||||
assert(k < (int)leftSVecs.cols());
|
||||
Field svec(Grid);
|
||||
svec = Zero();
|
||||
for (int j = 0; j < Nm; ++j)
|
||||
svec = svec + leftSVecs(j, k) * U[j];
|
||||
return svec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the k-th approximate right singular vector of A in the full
|
||||
* lattice space. computeSVD() must have been called first.
|
||||
*/
|
||||
Field rightSingularVector(int k)
|
||||
{
|
||||
assert(k < (int)rightSVecs.cols());
|
||||
Field svec(Grid);
|
||||
svec = Zero();
|
||||
for (int j = 0; j < Nm; ++j)
|
||||
svec = svec + rightSVecs(j, k) * V[j];
|
||||
return svec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the bidiagonalization: returns max residual
|
||||
* max_k || A v_k - alpha_k u_k - beta_k u_{k-1} ||
|
||||
*/
|
||||
RealD verify()
|
||||
{
|
||||
Field tmp(Grid);
|
||||
RealD maxres = 0.0;
|
||||
for (int k = 0; k < Nm; ++k) {
|
||||
Linop.Op(V[k], tmp);
|
||||
tmp = tmp - alpha[k] * U[k];
|
||||
if (k > 0 && k-1 < (int)beta.size())
|
||||
tmp = tmp - beta[k-1] * U[k-1];
|
||||
RealD res = std::sqrt(norm2(tmp));
|
||||
if (res > maxres) maxres = res;
|
||||
std::cout << GridLogMessage
|
||||
<< "LanczosBidiagonalization verify step " << k
|
||||
<< " ||A v_k - alpha_k u_k - beta_{k-1} u_{k-1}|| = "
|
||||
<< res << std::endl;
|
||||
}
|
||||
return maxres;
|
||||
}
|
||||
|
||||
/* Getters */
|
||||
int getNm() const { return Nm; }
|
||||
const std::vector<Field>& getV() const { return V; }
|
||||
const std::vector<Field>& getU() const { return U; }
|
||||
const std::vector<RealD>& getAlpha() const { return alpha; }
|
||||
const std::vector<RealD>& getBeta() const { return beta; }
|
||||
Eigen::VectorXd getSingularValues() const { return singularValues; }
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
#endif
|
||||
@@ -236,5 +236,4 @@ public:
|
||||
}
|
||||
};
|
||||
NAMESPACE_END(Grid);
|
||||
#undef GCRLogLevel
|
||||
#endif
|
||||
@@ -38,14 +38,13 @@ Author: Peter Boyle <paboyle@ph.ed.ac.uk>
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
#define GCRLogLevel std::cout << GridLogMessage <<std::string(level,'\t')<< name<<" "
|
||||
#define GCRLogLevel std::cout << GridLogMessage <<std::string(level,'\t')<< " Level "<<level<<" "
|
||||
|
||||
template<class Field>
|
||||
class PrecGeneralisedConjugateResidualNonHermitian : public LinearFunction<Field> {
|
||||
public:
|
||||
using LinearFunction<Field>::operator();
|
||||
RealD Tolerance;
|
||||
RealD SSQ;
|
||||
Integer MaxIterations;
|
||||
int verbose;
|
||||
int mmax;
|
||||
@@ -55,37 +54,40 @@ public:
|
||||
GridStopWatch PrecTimer;
|
||||
GridStopWatch MatTimer;
|
||||
GridStopWatch LinalgTimer;
|
||||
std::string name;
|
||||
int ZeroGuess = 0; // caller contract: guess is always zero => first-cycle r0 = src, skip the apply
|
||||
int FirstCycle = 0;
|
||||
|
||||
LinearFunction<Field> &Preconditioner;
|
||||
LinearOperatorBase<Field> &Linop;
|
||||
|
||||
void Name(std::string _name) { name = _name; };
|
||||
void Level(int lv) { level=lv; };
|
||||
|
||||
void Level(int n) { Name("Level " + std::to_string(n)); level = n; }
|
||||
|
||||
void SetZeroGuess(int z) { ZeroGuess = z; };
|
||||
|
||||
PrecGeneralisedConjugateResidualNonHermitian(RealD tol,Integer maxit,LinearOperatorBase<Field> &_Linop,LinearFunction<Field> &Prec,int _mmax,int _nstep) :
|
||||
PrecGeneralisedConjugateResidualNonHermitian(RealD tol,Integer maxit,LinearOperatorBase<Field> &_Linop,LinearFunction<Field> &Prec,int _mmax, int _nstep) :
|
||||
Tolerance(tol),
|
||||
MaxIterations(maxit),
|
||||
Linop(_Linop),
|
||||
Preconditioner(Prec),
|
||||
mmax(_mmax),
|
||||
nstep(_nstep)
|
||||
{
|
||||
Level(1);
|
||||
nstep(_nstep) // what is nstep vs mmax? one is the number of inner iterations
|
||||
{
|
||||
level=1;
|
||||
verbose=1;
|
||||
};
|
||||
|
||||
// virtual method stubs for updating GCR polynomial
|
||||
virtual void LogBegin(void){
|
||||
std::cout << "GCR::LogBegin() "<<std::endl;
|
||||
};
|
||||
virtual void LogIteration(int k, ComplexD a, std::vector<ComplexD> betas){
|
||||
std::cout << "GCR::LogIteration() "<<std::endl;
|
||||
};
|
||||
virtual void LogComplete(std::vector<ComplexD>& alphas, std::vector<std::vector<ComplexD>>& betas) {
|
||||
std::cout << "GCR::LogComplete() "<<std::endl;
|
||||
};
|
||||
|
||||
void operator() (const Field &src, Field &psi){
|
||||
|
||||
// psi=Zero();
|
||||
RealD cp, ssq,rsq;
|
||||
ssq=norm2(src);
|
||||
SSQ=ssq;
|
||||
rsq=Tolerance*Tolerance*ssq;
|
||||
|
||||
Field r(src.Grid());
|
||||
@@ -98,27 +100,25 @@ public:
|
||||
SolverTimer.Start();
|
||||
|
||||
steps=0;
|
||||
FirstCycle=1;
|
||||
for(int k=0;k<MaxIterations;k++){
|
||||
|
||||
cp=GCRnStep(src,psi,rsq);
|
||||
|
||||
GCRLogLevel <<"PGCR("<<mmax<<","<<nstep<<") "<< steps <<" steps cp = "<<sqrt(cp/ssq)<<" target "<<sqrt(rsq/ssq) <<std::endl;
|
||||
GCRLogLevel <<"PGCR("<<mmax<<","<<nstep<<") "<< steps <<" steps cp = "<<cp<<" target "<<rsq <<std::endl;
|
||||
|
||||
if(cp<rsq) {
|
||||
SolverTimer.Stop();
|
||||
|
||||
SolverTimer.Stop();
|
||||
Linop.Op(psi,r);
|
||||
axpy(r,-1.0,src,r);
|
||||
RealD tr = norm2(r);
|
||||
GCRLogLevel<<"PGCR: Converged on iteration " <<steps
|
||||
<< " computed residual "<<sqrt(cp/ssq)
|
||||
<< " true residual " <<sqrt(tr/ssq)
|
||||
<< " target " <<Tolerance <<std::endl;
|
||||
|
||||
Linop.Op(psi,r);
|
||||
axpy(r,-1.0,src,r);
|
||||
RealD tr = norm2(r);
|
||||
GCRLogLevel<<"PGCR: Converged on iteration " <<steps
|
||||
<< " computed residual "<<sqrt(cp/ssq)
|
||||
<< " true residual " <<sqrt(tr/ssq)
|
||||
<< " target " <<Tolerance <<std::endl;
|
||||
|
||||
GCRLogLevel<<"PGCR Time elapsed: Total "<< SolverTimer.Elapsed() <<std::endl;
|
||||
return;
|
||||
GCRLogLevel<<"PGCR Time elapsed: Total "<< SolverTimer.Elapsed() <<std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -145,32 +145,30 @@ public:
|
||||
////////////////////////////////
|
||||
// history for flexible orthog
|
||||
////////////////////////////////
|
||||
std::vector<Field> q(mmax,grid);
|
||||
std::vector<Field> p(mmax,grid);
|
||||
std::vector<RealD> qq(mmax);
|
||||
std::vector<Field> q(mmax,grid); // q = Ap
|
||||
std::vector<Field> p(mmax,grid); // store mmax conjugate momenta
|
||||
std::vector<RealD> qq(mmax); // qq = (Ap)^2 = <p|A^\dagger A |p> (denom of \alpha)
|
||||
|
||||
GCRLogLevel<< "PGCR nStep("<<nstep<<")"<<std::endl;
|
||||
|
||||
//////////////////////////////////
|
||||
// r0 = src - A x0. ZeroGuess: on the first cycle x0==0 by caller
|
||||
// contract (enforced here), so r0 = src exactly; skip the apply.
|
||||
// Restart cycles (psi!=0) always do the full computation.
|
||||
// initial guess x0 is taken as nonzero.
|
||||
// r0=src-A x0 = src
|
||||
//////////////////////////////////
|
||||
if (ZeroGuess && FirstCycle) {
|
||||
psi = Zero();
|
||||
LinalgTimer.Start();
|
||||
r = src;
|
||||
LinalgTimer.Stop();
|
||||
} else {
|
||||
MatTimer.Start();
|
||||
Linop.Op(psi,Az);
|
||||
MatTimer.Stop();
|
||||
LinalgTimer.Start();
|
||||
r=src-Az;
|
||||
LinalgTimer.Stop();
|
||||
}
|
||||
FirstCycle=0;
|
||||
MatTimer.Start();
|
||||
Linop.Op(psi,Az);
|
||||
// zAz = innerProduct(Az,psi);
|
||||
zAAz= norm2(Az);
|
||||
MatTimer.Stop();
|
||||
|
||||
|
||||
LinalgTimer.Start();
|
||||
r=src-Az;
|
||||
LinalgTimer.Stop();
|
||||
GCRLogLevel<< "PGCR true residual r = src - A psi "<< norm2(r) <<std::endl;
|
||||
|
||||
this->LogBegin(); // initialize polynomial GCR if needed (TODO think about placement of this)
|
||||
|
||||
/////////////////////
|
||||
// p = Prec(r)
|
||||
/////////////////////
|
||||
@@ -192,33 +190,46 @@ public:
|
||||
p[0]= z;
|
||||
q[0]= Az;
|
||||
qq[0]= zAAz;
|
||||
|
||||
std::cout << "||init p - src||: " << norm2(p[0] - src) << std::endl; // for debugging
|
||||
|
||||
cp =norm2(r);
|
||||
LinalgTimer.Stop();
|
||||
GCRLogLevel<< "PGCR true residual "<< sqrt(cp/SSQ) <<std::endl;
|
||||
|
||||
std::vector<ComplexD> all_alphas;
|
||||
std::vector<std::vector<ComplexD>> all_betas;
|
||||
|
||||
for(int k=0;k<nstep;k++){
|
||||
|
||||
steps++;
|
||||
|
||||
int kp = k+1;
|
||||
int peri_k = k %mmax;
|
||||
int peri_k = k %mmax; // only store mmax vectors; just roll around if needed
|
||||
int peri_kp= kp%mmax;
|
||||
|
||||
// std::cout << "peri_kp = " << peri_kp << std::endl;
|
||||
|
||||
LinalgTimer.Start();
|
||||
rq= innerProduct(q[peri_k],r); // what if rAr not real?
|
||||
a = rq/qq[peri_k];
|
||||
a = rq/qq[peri_k]; // compute alpha_j
|
||||
|
||||
axpy(psi,a,p[peri_k],psi);
|
||||
all_alphas.push_back(a);
|
||||
|
||||
cp = axpy_norm(r,-a,q[peri_k],r);
|
||||
axpy(psi,a,p[peri_k],psi); // update psi --> psi + \alpha p
|
||||
|
||||
cp = axpy_norm(r,-a,q[peri_k],r); // update r --> r - \alpha D p. Note q = Dp
|
||||
LinalgTimer.Stop();
|
||||
|
||||
GCRLogLevel<< "PGCR step["<<steps<<"] resid " << sqrt(cp/SSQ)<<std::endl;
|
||||
// LogIterationA(k + 1, a);
|
||||
|
||||
GCRLogLevel<< "GCR step["<<steps<<"] resid " << cp << " target " <<rsq<<std::endl;
|
||||
|
||||
// moving this to end of loop so that it doesn't exit beforehand
|
||||
// TODO if I want to uncomment this, I have to split the LogIteration again and put LogIterationA() beforehand
|
||||
// if((k==nstep-1)||(cp<rsq)){
|
||||
// return cp;
|
||||
// }
|
||||
|
||||
if((k==nstep-1)||(cp<rsq)){
|
||||
return cp;
|
||||
}
|
||||
|
||||
PrecTimer.Start();
|
||||
Preconditioner(r,z);// solve Az = r
|
||||
@@ -235,24 +246,205 @@ public:
|
||||
q[peri_kp]=Az;
|
||||
p[peri_kp]=z;
|
||||
|
||||
// Field Dsrc (grid);
|
||||
// Linop.Op(src, Dsrc);
|
||||
// std::cout << "||q[peri_kp] - D(src)||: " << norm2(q[peri_kp] - Dsrc) << std::endl; // for debugging
|
||||
|
||||
// // delete after testing
|
||||
// std::cout << "Testing Dsq on one for GCR: " << std::endl;
|
||||
// Field myField (grid);
|
||||
// myField = 1.0;
|
||||
// Field out1 (grid); Field out2 (grid);
|
||||
// Linop.HermOp(myField, out1);
|
||||
// Linop.Op(myField, out2);
|
||||
// std::cout << "Dsq.Hermop(ones) has norm " << norm2(out1) << std::endl;
|
||||
// std::cout << "Dsq.Op(ones) has norm " << norm2(out2) << std::endl;
|
||||
|
||||
// basically northog = k+1 if mmax is large
|
||||
int northog = ((kp)>(mmax-1))?(mmax-1):(kp); // if more than mmax done, we orthog all mmax history.
|
||||
// std::cout << "northog: " << northog << std::endl;
|
||||
std::vector<ComplexD> betas (northog);
|
||||
// std::cout << "peri_kp: " << peri_kp << std::endl;
|
||||
// we iterate backwards counting down from the current k+1 index (peri_kp) because we
|
||||
for(int back=0;back<northog;back++){
|
||||
|
||||
int peri_back=(k-back)%mmax; GRID_ASSERT((k-back)>=0);
|
||||
|
||||
b=-real(innerProduct(q[peri_back],Az))/qq[peri_back];
|
||||
p[peri_kp]=p[peri_kp]+b*p[peri_back];
|
||||
q[peri_kp]=q[peri_kp]+b*q[peri_back];
|
||||
// b=-real(innerProduct(q[peri_back],Az))/qq[peri_back];
|
||||
b=-(innerProduct(q[peri_back],Az))/qq[peri_back]; // TODO try complex beta
|
||||
p[peri_kp]=p[peri_kp]+b*p[peri_back];
|
||||
q[peri_kp]=q[peri_kp]+b*q[peri_back];
|
||||
|
||||
// LogIterationB(peri_back, b);
|
||||
// betas[back] = b; // may need to change the indexing if I ever do it with restarts
|
||||
// std::cout << "[DEBUG] pushing beta for back = " << back << ", peri_back = " << peri_back << std::endl;
|
||||
|
||||
betas[peri_back] = b; // may need to change the indexing if I ever do it with restarts
|
||||
|
||||
}
|
||||
qq[peri_kp]=norm2(q[peri_kp]); // could use axpy_norm
|
||||
LinalgTimer.Stop();
|
||||
|
||||
// log iteration and update GCR polynomial if necessary.
|
||||
all_betas.push_back(betas);
|
||||
LogIteration(k + 1, a, betas);
|
||||
|
||||
// finish if necessary
|
||||
if((k==nstep-1)||(cp<rsq)){
|
||||
std::cout << "All alphas: " << std::endl << all_alphas << std::endl;
|
||||
std::cout << "All betas: " << std::endl << all_betas << std::endl;
|
||||
LogComplete(all_alphas, all_betas);
|
||||
std::cout << "Exiting GCR." << std::endl;
|
||||
return cp;
|
||||
}
|
||||
|
||||
}
|
||||
GRID_ASSERT(0); // never reached
|
||||
return cp;
|
||||
}
|
||||
};
|
||||
NAMESPACE_END(Grid);
|
||||
|
||||
#undef GCRLogLevel
|
||||
class PolynomialFile: Serializable {
|
||||
public:
|
||||
GRID_SERIALIZABLE_CLASS_MEMBERS(PolynomialFile,
|
||||
std::vector<std::vector<std::complex<double>>>, data,
|
||||
std::vector<std::vector<std::complex<double>>>, betas,
|
||||
std::vector<std::complex<double>>, alphas
|
||||
);
|
||||
};
|
||||
|
||||
// Optionally record the GCR polynomial. [PO]: TODO
|
||||
template <class Field>
|
||||
class PGCRPolynomial : public PrecGeneralisedConjugateResidualNonHermitian<Field> {
|
||||
public:
|
||||
std::vector<ComplexD> ak;
|
||||
std::vector<std::vector<ComplexD>> bk;
|
||||
// std::vector<ComplexD> poly_p;
|
||||
std::vector<std::vector<ComplexD>> poly_p;
|
||||
std::vector<ComplexD> poly_Ap; // polynomial in Ap_j (only store it for last p)
|
||||
std::vector<ComplexD> poly_r;
|
||||
std::vector<ComplexD> polynomial;
|
||||
|
||||
PolynomialFile& PF;
|
||||
|
||||
public:
|
||||
PGCRPolynomial(RealD tol, Integer maxit,LinearOperatorBase<Field> &_Linop, LinearFunction<Field> &Prec, int _mmax, int _nstep, PolynomialFile& _PF)
|
||||
: PrecGeneralisedConjugateResidualNonHermitian<Field>(tol, maxit, _Linop, Prec, _mmax, _nstep), PF(_PF)
|
||||
{};
|
||||
|
||||
// think this applies the polynomial in A = Linop to a field src. The coeffs are
|
||||
// stored in the vector `polynomial`.
|
||||
void PolyOp(const Field &src, Field &psi)
|
||||
{
|
||||
Field tmp(src.Grid());
|
||||
Field AtoN(src.Grid());
|
||||
AtoN = src;
|
||||
psi=AtoN*polynomial[0];
|
||||
for(int n=1;n<polynomial.size();n++){
|
||||
tmp = AtoN;
|
||||
this->Linop.Op(tmp,AtoN); // iterate A^n
|
||||
psi = psi + polynomial[n]*AtoN; // psi += poly_n A^n src
|
||||
}
|
||||
}
|
||||
|
||||
// [PO TODO] debug this
|
||||
void PGCRsequence(const Field &src, Field &x)
|
||||
{
|
||||
Field Ap(src.Grid());
|
||||
Field r(src.Grid());
|
||||
// Field p(src.Grid());
|
||||
// p=src;
|
||||
std::vector<Field> p;
|
||||
p.push_back(src);
|
||||
r=src;
|
||||
x=Zero();
|
||||
x.Checkerboard()=src.Checkerboard();
|
||||
for(int k=0;k<ak.size();k++){
|
||||
x = x + ak[k]*p[k];
|
||||
this->Linop.Op(p[k], Ap);
|
||||
r = r - ak[k] * Ap;
|
||||
// p[k] = r;
|
||||
p.push_back(r);
|
||||
for (int i = 0; i < k; i++) { // [PO TODO] check indices
|
||||
p[k+1] += bk[i, k+1] * p[i];
|
||||
}
|
||||
// p = r + bk[k] * p;
|
||||
}
|
||||
}
|
||||
|
||||
void Solve(const Field &src, Field &psi)
|
||||
{
|
||||
psi=Zero();
|
||||
this->operator()(src, psi);
|
||||
}
|
||||
|
||||
virtual void LogBegin(void)
|
||||
{
|
||||
std::cout << "PGCR::LogBegin() "<<std::endl;
|
||||
ak.resize(0);
|
||||
bk.resize(0);
|
||||
polynomial.resize(0);
|
||||
poly_Ap.push_back(0.0); // start with (0.0); during first iteration should change to (0.0, 1.0)
|
||||
std::vector<ComplexD> p0_tmp;
|
||||
p0_tmp.push_back(1.0);
|
||||
poly_p.push_back(p0_tmp);
|
||||
poly_r.push_back(1.0);
|
||||
};
|
||||
|
||||
// Updates vector psi and r and initializes vector p[k+1]
|
||||
virtual void LogIteration(int k, ComplexD a, std::vector<ComplexD> betas){
|
||||
std::cout << "PGCR::LogIteration(k = " << k << ")" << std::endl;
|
||||
ak.push_back(a);
|
||||
bk.push_back(betas);
|
||||
|
||||
// update Ap by pushing p[k] to the right
|
||||
poly_Ap.push_back(0.0); // need to pad the end with an element
|
||||
poly_Ap[0] = 0.0; // technically this should be unnecessary, as the first component is never set
|
||||
for(int i = 0; i < k; i++){
|
||||
poly_Ap[i+1]=poly_p[k-1][i]; // A\vec{p} = (0, \vec{p}) bc A shifts components of p to the right
|
||||
}
|
||||
|
||||
// update psi_{k+1} --> psi_k + a_k p_k
|
||||
polynomial.push_back(0.0);
|
||||
for(int i = 0; i < k; i++) {
|
||||
polynomial[i] += a * poly_p[k-1][i];
|
||||
}
|
||||
{
|
||||
std::vector<std::complex<double>> poly_stdcmplx(polynomial.begin(), polynomial.end());
|
||||
PF.data.push_back(poly_stdcmplx);
|
||||
}
|
||||
|
||||
// r_{k+1} --> r_k - a_k A p_k
|
||||
// p_{k+1} --> r_k + \sum_{i=0}^k \beta_{ik} p_i, input betas = (\beta_{ik})_i
|
||||
poly_r.push_back(0.0); // should be of size k+1 if we start with k = 1
|
||||
std::vector<ComplexD> p_next (k + 1, ComplexD(0.0)); // p_{k+1} = same size as r_{k+1}
|
||||
for(int i = 0; i < k + 1; i++){
|
||||
poly_r[i] = poly_r[i] - a * poly_Ap[i]; // update r_{k+1} --> r_k - \alpha_k A p_k
|
||||
p_next[i] = poly_r[i]; // init new vector as r_{k+1}
|
||||
}
|
||||
|
||||
// p_{k+1} --> p_{k+1} + \sum_i \beta_{ij} p_i
|
||||
int nbeta = betas.size();
|
||||
std::cout << "Betas: " << betas << std::endl;
|
||||
for (int j = 0; j < nbeta; j++) {
|
||||
for (int i = 0; i < j+1; i++) {
|
||||
p_next[i] += betas[j] * poly_p[j][i];
|
||||
}
|
||||
}
|
||||
poly_p.push_back(p_next); // add p_{k+1} to the list of p's
|
||||
}
|
||||
|
||||
virtual void LogComplete(std::vector<ComplexD>& alphas, std::vector<std::vector<ComplexD>>& betas) {
|
||||
/** Logs all alphas and betas to complete the iterations. */
|
||||
std::cout << "PGCR::LogComplete() "<<std::endl;
|
||||
for (int i = 0; i < alphas.size(); i++) {
|
||||
PF.alphas.push_back(std::complex<double>(alphas[i].real(), alphas[i].imag()));
|
||||
std::vector<std::complex<double>> beta_stdcmplx(betas[i].begin(), betas[i].end());
|
||||
PF.betas.push_back(beta_stdcmplx);
|
||||
}
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
#endif
|
||||
@@ -0,0 +1,753 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./Grid/algorithms/iterative/RestartedLanczosBidiagonalization.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Chulwoo Jung <chulwoo@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_RESTARTED_LANCZOS_BIDIAGONALIZATION_H
|
||||
#define GRID_RESTARTED_LANCZOS_BIDIAGONALIZATION_H
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
/**
|
||||
* Implicitly Restarted Lanczos Bidiagonalization (IRLBA)
|
||||
*
|
||||
* Computes the p largest (or p smallest) singular triplets of a linear
|
||||
* operator A using the Golub-Kahan-Lanczos bidiagonalization with implicit
|
||||
* restart via thick-restart / QR shifts.
|
||||
*
|
||||
* Algorithm (Baglama & Reichel, SIAM J. Sci. Comput. 27(1):19-42, 2005):
|
||||
*
|
||||
* Outer loop:
|
||||
* 1. Extend the p-step (or seed) bidiagonalization to k steps:
|
||||
* A V_k = U_k B_k
|
||||
* A^dag U_k = V_k B_k^T + beta_{k+1} v_{k+1} e_k^T
|
||||
* 2. Compute SVD: B_k = X Sigma Y^T
|
||||
* 3. Check convergence of the p desired singular values via
|
||||
* |beta_{k+1} * y_{k,i}| < tol * sigma_i
|
||||
* where y_{k,i} is the last component of the i-th right singular vector.
|
||||
* 4. Apply k-p implicit QR shifts to implicitly compress the basis
|
||||
* to p steps (Sorensen-Lehoucq thick restart):
|
||||
* B_p^+ = X_p^T B_k Y_p (upper bidiagonal, p x p)
|
||||
* and update the lattice vectors:
|
||||
* V_p^+ = V_k Y_p
|
||||
* U_p^+ = U_k X_p
|
||||
* The new residual coupling is
|
||||
* beta_p^+ v_{p+1}^+ = beta_{k+1} v_{k+1} * (e_k^T Y_p)_p
|
||||
* + B_k(p,p+1) * (orthogonal tail from QR)
|
||||
* 5. Go to step 1.
|
||||
*
|
||||
* Template parameter
|
||||
* ------------------
|
||||
* Field : lattice field type (must support Grid algebra operations)
|
||||
*
|
||||
* Usage
|
||||
* -----
|
||||
* RestartedLanczosBidiagonalization<Field> irlba(Linop, grid, p, k, tol, maxIter);
|
||||
* irlba.run(src);
|
||||
* // Results available via getters.
|
||||
*/
|
||||
template <class Field>
|
||||
class RestartedLanczosBidiagonalization {
|
||||
|
||||
public:
|
||||
LinearOperatorBase<Field> &Linop;
|
||||
GridBase *Grid;
|
||||
|
||||
int Nk; // number of desired singular triplets
|
||||
int Nm; // Lanczos basis size (Nm > Nk)
|
||||
RealD Tolerance;
|
||||
int MaxIter;
|
||||
bool largest; // if true, target largest singular values; otherwise smallest
|
||||
|
||||
// Converged singular triplets (filled after run())
|
||||
std::vector<RealD> singularValues; // sigma_0 >= sigma_1 >= ...
|
||||
std::vector<Field> leftVectors; // approximate left singular vectors
|
||||
std::vector<Field> rightVectors; // approximate right singular vectors
|
||||
|
||||
private:
|
||||
// Working bases (size up to Nm+1)
|
||||
std::vector<Field> V; // right Lanczos vectors
|
||||
std::vector<Field> U; // left Lanczos vectors
|
||||
std::vector<RealD> alpha;
|
||||
std::vector<RealD> beta;
|
||||
|
||||
// After a thick restart, the column at index restart_col of U^dag A V
|
||||
// has extra non-zero entries (rows 0..restart_col-2) beyond what the
|
||||
// upper bidiagonal captures. fvec[j] = <U[j] | A V[restart_col]> for
|
||||
// j = 0..restart_col-1. (fvec[restart_col-1] == beta[restart_col-1].)
|
||||
// reset_col == -1 means no restart has occurred yet (pure bidiagonal).
|
||||
std::vector<RealD> fvec;
|
||||
int restart_col;
|
||||
|
||||
public:
|
||||
|
||||
RestartedLanczosBidiagonalization(LinearOperatorBase<Field> &_Linop,
|
||||
GridBase *_Grid,
|
||||
int _Nk, int _Nm,
|
||||
RealD _tol = 1.0e-8,
|
||||
int _maxIt = 300,
|
||||
bool _largest = true)
|
||||
: Linop(_Linop), Grid(_Grid),
|
||||
Nk(_Nk), Nm(_Nm),
|
||||
Tolerance(_tol), MaxIter(_maxIt),
|
||||
largest(_largest)
|
||||
{
|
||||
assert(Nm > Nk);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run IRLBA starting from src.
|
||||
* On exit, singularValues, leftVectors, rightVectors are filled with
|
||||
* the Nk converged singular triplets.
|
||||
*/
|
||||
void run(const Field &src)
|
||||
{
|
||||
assert(norm2(src) > 0.0);
|
||||
|
||||
singularValues.clear();
|
||||
leftVectors.clear();
|
||||
rightVectors.clear();
|
||||
|
||||
// Allocate working bases
|
||||
V.clear(); U.clear();
|
||||
alpha.clear(); beta.clear();
|
||||
fvec.clear(); restart_col = -1;
|
||||
V.reserve(Nm + 1);
|
||||
U.reserve(Nm);
|
||||
|
||||
// Seed: v_0 = src / ||src||
|
||||
Field vtmp(Grid);
|
||||
vtmp = src;
|
||||
RealD nrm = std::sqrt(norm2(vtmp));
|
||||
vtmp = (1.0 / nrm) * vtmp;
|
||||
V.push_back(vtmp);
|
||||
|
||||
int pStart = 0; // current basis size at start of extension
|
||||
RealD betaRestart = 0.0; // coupling from previous restart
|
||||
|
||||
for (int iter = 0; iter < MaxIter; ++iter) {
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Step 1: extend from pStart steps to Nm steps
|
||||
// ----------------------------------------------------------------
|
||||
extendBasis(pStart, Nm, betaRestart);
|
||||
// verify();
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Step 2: SVD of the Nm x Nm B matrix.
|
||||
// iter=0 (pStart==0): B is exactly bidiagonal — use buildBidiagonal.
|
||||
// iter>0 (pStart==Nk): after a thick restart, column restart_col of
|
||||
// U^dag A V has extra off-diagonal entries captured by fvec; use
|
||||
// buildFullB so the Ritz values and restart vectors are computed from
|
||||
// the exact projected matrix A V = U B_full.
|
||||
// ----------------------------------------------------------------
|
||||
Eigen::MatrixXd B = (pStart == 0) ? buildBidiagonal(Nm) : buildFullB(Nm);
|
||||
Eigen::JacobiSVD<Eigen::MatrixXd> svd(B,
|
||||
Eigen::ComputeThinU | Eigen::ComputeThinV);
|
||||
|
||||
Eigen::VectorXd sigma = svd.singularValues(); // descending
|
||||
Eigen::MatrixXd X = svd.matrixU(); // Nm x Nm left SVecs of B
|
||||
Eigen::MatrixXd Y = svd.matrixV(); // Nm x Nm right SVecs of B
|
||||
|
||||
// If targeting smallest, reorder so desired ones come first
|
||||
Eigen::VectorXi order = sortOrder(sigma);
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Step 3: check convergence of the Nk desired singular values
|
||||
// ----------------------------------------------------------------
|
||||
RealD betaK = beta.back(); // beta_{k+1}
|
||||
// In our convention A V = U B (exact), the residual is in the A^dag
|
||||
// direction: A^dag u_j - sigma_j v_j = betaK * X[Nm-1,j] * V[Nm].
|
||||
// Convergence criterion: |betaK * X[Nm-1, idx]| < tol * sigma_idx.
|
||||
int nconv = 0;
|
||||
for (int i = 0; i < Nk; ++i) {
|
||||
int idx = order(i);
|
||||
RealD res = std::abs(betaK * X(Nm - 1, idx));
|
||||
RealD thr = Tolerance * std::max(sigma(idx), 1.0e-14);
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA iter " << iter
|
||||
<< " sigma[" << i << "] = " << sigma(idx)
|
||||
<< " res = " << res
|
||||
<< " thr = " << thr << std::endl;
|
||||
if (res < thr) ++nconv;
|
||||
else break; // residuals not strictly ordered but break is conservative
|
||||
}
|
||||
|
||||
if (nconv >= Nk) {
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA converged: " << nconv << " singular values after "
|
||||
<< iter + 1 << " iterations." << std::endl;
|
||||
// Collect converged triplets
|
||||
extractTriplets(Nm, sigma, X, Y, order, Nk);
|
||||
return;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Step 4: implicit restart — compress to Nk steps
|
||||
// ----------------------------------------------------------------
|
||||
implicitRestart(Nm, Nk, sigma, X, Y, order, betaK, betaRestart);
|
||||
// verify();
|
||||
|
||||
// Lucky breakdown: exact invariant subspace found; convergence is exact.
|
||||
// B_p^+ = diag(alpha[0..Nk-1]); extract directly from restart basis.
|
||||
if (betaRestart < 1.0e-14) {
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA: lucky breakdown after restart (betaRestart = 0)."
|
||||
<< " Extracting " << Nk << " exact Ritz triplets." << std::endl;
|
||||
// Re-run SVD on the p-step diagonal B^+ to get sorted Ritz triplets.
|
||||
Eigen::MatrixXd Bp = buildBidiagonal(Nk);
|
||||
Eigen::JacobiSVD<Eigen::MatrixXd> svdp(Bp,
|
||||
Eigen::ComputeThinU | Eigen::ComputeThinV);
|
||||
Eigen::VectorXi ordp = sortOrder(svdp.singularValues());
|
||||
extractTriplets(Nk, svdp.singularValues(), svdp.matrixU(),
|
||||
svdp.matrixV(), ordp, Nk);
|
||||
return;
|
||||
}
|
||||
|
||||
pStart = Nk;
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA: did not converge in " << MaxIter
|
||||
<< " iterations. Returning best approximations." << std::endl;
|
||||
|
||||
// Return best available approximations
|
||||
Eigen::MatrixXd B = buildFullB((int)alpha.size());
|
||||
Eigen::JacobiSVD<Eigen::MatrixXd> svd(B,
|
||||
Eigen::ComputeThinU | Eigen::ComputeThinV);
|
||||
Eigen::VectorXd sigma = svd.singularValues();
|
||||
Eigen::MatrixXd X = svd.matrixU();
|
||||
Eigen::MatrixXd Y = svd.matrixV();
|
||||
Eigen::VectorXi order = sortOrder(sigma);
|
||||
int nout = std::min(Nk, (int)alpha.size());
|
||||
extractTriplets((int)alpha.size(), sigma, X, Y, order, nout);
|
||||
}
|
||||
|
||||
/* Getters */
|
||||
int getNk() const { return (int)singularValues.size(); }
|
||||
const std::vector<RealD>& getSingularValues() const { return singularValues; }
|
||||
const std::vector<Field>& getLeftVectors() const { return leftVectors; }
|
||||
const std::vector<Field>& getRightVectors() const { return rightVectors; }
|
||||
|
||||
/**
|
||||
* Print B_k and U^dag A V to verify the bidiagonalization relation
|
||||
* A V_m = U_m B_m (exact in our GK convention)
|
||||
* On the first call (pStart=0), max|B - U^dag A V| should be ~machine epsilon.
|
||||
* After a restart and extension, the column p of U^dag A V deviates from B
|
||||
* by O(betaK): this is expected because the thick restart breaks the Krylov
|
||||
* structure at column p, introducing off-diagonal terms proportional to betaK.
|
||||
* These terms vanish as betaK -> 0 (convergence), so the algorithm is correct.
|
||||
*/
|
||||
void verify()
|
||||
{
|
||||
int m = (int)alpha.size();
|
||||
int nU = (int)U.size();
|
||||
int nV = (int)V.size();
|
||||
if (m == 0) { std::cout << GridLogMessage << "IRLBA verify: empty basis" << std::endl; return; }
|
||||
|
||||
// Build reference matrix Bref (nU x nV):
|
||||
// Columns 0..m-1 : buildFullB(m) (bidiagonal + fvec column at restart_col)
|
||||
// Column m : residual column, two cases:
|
||||
// (a) restart_col == m (right after implicitRestart, before extendBasis):
|
||||
// V[m] = sgn*V_old[Nm], so <U[i]|A|V[m]> = fvec[i] for all i
|
||||
// (b) otherwise (pure GK or after extendBasis):
|
||||
// only entry (m-1, m) = beta[m-1] (GK recurrence residual)
|
||||
Eigen::MatrixXd Bref = Eigen::MatrixXd::Zero(nU, nV);
|
||||
{
|
||||
Eigen::MatrixXd Bfull = buildFullB(m);
|
||||
int cols = std::min(m, nV);
|
||||
Bref.block(0, 0, m, cols) = Bfull.block(0, 0, m, cols);
|
||||
}
|
||||
if (nV > m && m > 0) {
|
||||
if (restart_col == m && (int)fvec.size() == m) {
|
||||
// Case (a): right after implicitRestart
|
||||
for (int i = 0; i < m; ++i) Bref(i, m) = fvec[i];
|
||||
} else if ((int)beta.size() >= m) {
|
||||
// Case (b): standard GK residual column
|
||||
Bref(m - 1, m) = beta[m - 1];
|
||||
}
|
||||
}
|
||||
|
||||
// Compute M[i,j] = <U[i] | A | V[j]>
|
||||
Eigen::MatrixXd M = Eigen::MatrixXd::Zero(nU, nV);
|
||||
Field Avj(Grid);
|
||||
for (int j = 0; j < nV; ++j) {
|
||||
Linop.Op(V[j], Avj);
|
||||
for (int i = 0; i < nU; ++i) {
|
||||
ComplexD ip = innerProduct(U[i], Avj);
|
||||
M(i, j) = ip.real();
|
||||
}
|
||||
}
|
||||
|
||||
// Print Bref
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA verify: Bref (" << nU << "x" << nV << "):" << std::endl;
|
||||
for (int i = 0; i < nU; ++i) {
|
||||
std::cout << GridLogMessage << " row " << i << ": ";
|
||||
for (int j = 0; j < nV; ++j) std::cout << Bref(i,j) << " ";
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
// Print U^dag A V
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA verify: U^dag A V (" << nU << "x" << nV << "):" << std::endl;
|
||||
for (int i = 0; i < nU; ++i) {
|
||||
std::cout << GridLogMessage << " row " << i << ": ";
|
||||
for (int j = 0; j < nV; ++j) std::cout << M(i,j) << " ";
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
// Max deviation over the full nU x nV matrix
|
||||
RealD maxdev = (Bref - M).cwiseAbs().maxCoeff();
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA verify: max|Bref - U^dag A V| = " << maxdev << std::endl;
|
||||
|
||||
// Beta
|
||||
std::cout << GridLogMessage << "IRLBA verify: beta[0.." << (int)beta.size()-1 << "] = ";
|
||||
for (auto b : beta) std::cout << b << " ";
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Build the m x m upper-bidiagonal matrix from alpha[0..m-1], beta[0..m-2]
|
||||
// ------------------------------------------------------------------
|
||||
Eigen::MatrixXd buildBidiagonal(int m) const
|
||||
{
|
||||
Eigen::MatrixXd B = Eigen::MatrixXd::Zero(m, m);
|
||||
for (int k = 0; k < m; ++k) {
|
||||
B(k, k) = alpha[k];
|
||||
if (k + 1 < m && k < (int)beta.size())
|
||||
B(k, k + 1) = beta[k];
|
||||
}
|
||||
return B;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Build the full m x m B matrix, including the non-bidiagonal column
|
||||
// at restart_col that arises after a thick restart.
|
||||
//
|
||||
// After restart, A V[restart_col] has projections onto all U[0..restart_col-1]
|
||||
// (not just U[restart_col-1]). These are stored in fvec[0..restart_col-1]
|
||||
// and make column restart_col of U^dag A V non-bidiagonal.
|
||||
// ------------------------------------------------------------------
|
||||
Eigen::MatrixXd buildFullB(int m) const
|
||||
{
|
||||
Eigen::MatrixXd B = buildBidiagonal(m);
|
||||
if (restart_col >= 0 && restart_col < m && (int)fvec.size() > 0) {
|
||||
for (int j = 0; j < restart_col && j < (int)fvec.size(); ++j){
|
||||
B(j, restart_col) = fvec[j];
|
||||
std::cout << GridLogDebug << "buildFullB: B " <<j<<" "<<restart_col<<B(j, restart_col)<<std::endl;
|
||||
}
|
||||
}
|
||||
return B;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Return a permutation vector that puts the desired Nk singular values
|
||||
// first (largest first if largest==true, smallest first otherwise).
|
||||
// Eigen's JacobiSVD already returns sigma in descending order, so for
|
||||
// largest we just return 0,1,...,m-1; for smallest we reverse.
|
||||
// ------------------------------------------------------------------
|
||||
Eigen::VectorXi sortOrder(const Eigen::VectorXd &sigma) const
|
||||
{
|
||||
int m = (int)sigma.size();
|
||||
Eigen::VectorXi ord(m);
|
||||
if (largest) {
|
||||
for (int i = 0; i < m; ++i) ord(i) = i;
|
||||
} else {
|
||||
for (int i = 0; i < m; ++i) ord(i) = m - 1 - i;
|
||||
}
|
||||
return ord;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Extend the Lanczos bidiagonalization from pStart to kEnd steps.
|
||||
// On first call pStart==0 (V[0] already set).
|
||||
// On restart calls V[0..pStart], U[0..pStart-1], alpha[0..pStart-1],
|
||||
// beta[0..pStart-1] are already set; betaRestart is the coupling
|
||||
// beta_{pStart} that drives the first new U step.
|
||||
// ------------------------------------------------------------------
|
||||
void extendBasis(int pStart, int kEnd, RealD betaRestart)
|
||||
{
|
||||
// Truncate containers to pStart (Lattice has no default constructor)
|
||||
if ((int)V.size() > pStart + 1) V.erase(V.begin() + pStart + 1, V.end());
|
||||
if ((int)U.size() > pStart) U.erase(U.begin() + pStart, U.end());
|
||||
alpha.resize(pStart);
|
||||
beta.resize(pStart);
|
||||
|
||||
Field p(Grid), r(Grid);
|
||||
|
||||
for (int k = pStart; k < kEnd; ++k) {
|
||||
|
||||
// p = A v_k
|
||||
Linop.Op(V[k], p);
|
||||
|
||||
// Remove previous left vector coupling
|
||||
if (k > 0) {
|
||||
p = p - beta[k - 1] * U[k - 1];
|
||||
}
|
||||
// On the first step after a restart, beta[pStart-1] was already set;
|
||||
// but V[pStart] was already constructed including the beta correction,
|
||||
// so no extra subtraction needed here beyond the standard recurrence.
|
||||
|
||||
// Reorthogonalize p against U, then alpha_k = ||p||, u_k = p/alpha_k
|
||||
reorthogonalize(p, U);
|
||||
RealD ak = std::sqrt(norm2(p));
|
||||
if (ak < 1.0e-14) {
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA extendBasis: lucky breakdown at step " << k
|
||||
<< " (alpha = " << ak << ")" << std::endl;
|
||||
alpha.push_back(ak);
|
||||
Field zero(Grid); zero = Zero();
|
||||
U.push_back(zero);
|
||||
beta.push_back(0.0);
|
||||
V.push_back(zero);
|
||||
break;
|
||||
}
|
||||
alpha.push_back(ak);
|
||||
|
||||
Field u(Grid);
|
||||
u = (1.0 / ak) * p;
|
||||
U.push_back(u);
|
||||
|
||||
// r = A^dag u_k - alpha_k v_k, reorthogonalize, then beta_{k+1} = ||r||
|
||||
Linop.AdjOp(U[k], r);
|
||||
r = r - ak * V[k];
|
||||
reorthogonalize(r, V);
|
||||
|
||||
RealD bk = std::sqrt(norm2(r));
|
||||
beta.push_back(bk);
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA extend step " << k
|
||||
<< " alpha = " << ak
|
||||
<< " beta = " << bk << std::endl;
|
||||
|
||||
// Always push v_{k+1} (needed as residual direction for restart)
|
||||
if (bk < 1.0e-14) {
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA extendBasis: lucky breakdown (beta = 0) at step "
|
||||
<< k << std::endl;
|
||||
Field zero(Grid); zero = Zero();
|
||||
V.push_back(zero);
|
||||
break;
|
||||
}
|
||||
Field vnext(Grid);
|
||||
vnext = (1.0 / bk) * r;
|
||||
V.push_back(vnext);
|
||||
|
||||
if (k == kEnd - 1) break; // v_{k+1} pushed above; stop here
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
// ------------------------------------------------------------------
|
||||
// Block reorthogonalization helpers.
|
||||
// Declared public because CUDA extended lambdas cannot live inside
|
||||
// private/protected member functions.
|
||||
//
|
||||
// batchInnerProducts: computes c[j] = <basis[j], vec> for all j
|
||||
// in a single GPU pass (one accelerator_barrier instead of n).
|
||||
// Queues n pairs of (per-site kernel, reduceKernel) to computeStream
|
||||
// without intermediate CPU syncs, then syncs once at the end.
|
||||
//
|
||||
// batchUpdate: computes vec -= sum_j c[j]*basis[j] in one GPU kernel.
|
||||
//
|
||||
// reorthogonalize: two-pass Classical Gram-Schmidt (CGS2) using the
|
||||
// two helpers above. Each pass costs 2 GPU syncs (1 IP + 1 update)
|
||||
// instead of 2n syncs per pass in the old sequential MGS.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
void batchInnerProducts(const Field &vec,
|
||||
const std::vector<Field> &basis,
|
||||
std::vector<ComplexD> &c)
|
||||
{
|
||||
int n = (int)basis.size();
|
||||
c.resize(n);
|
||||
if (n == 0) return;
|
||||
|
||||
typedef typename Field::vector_object vobj;
|
||||
typedef decltype(innerProduct(vobj(), vobj())) inner_t;
|
||||
typedef decltype(basis[0].View(AcceleratorRead)) View;
|
||||
|
||||
GridBase *grid = vec.Grid();
|
||||
uint64_t oSites = grid->oSites();
|
||||
uint64_t nsimd = grid->Nsimd();
|
||||
|
||||
// all_ip[j * oSites + ss] = per-site inner product of basis[j] and vec at site ss.
|
||||
// Layout: n contiguous blocks of oSites each.
|
||||
deviceVector<inner_t> all_ip((uint64_t)n * oSites);
|
||||
inner_t *all_ip_p = &all_ip[0];
|
||||
|
||||
hostVector<View> h_basis_v(n);
|
||||
deviceVector<View> d_basis_v(n);
|
||||
for (int j = 0; j < n; ++j) {
|
||||
h_basis_v[j] = basis[j].View(AcceleratorRead);
|
||||
acceleratorPut(d_basis_v[j], h_basis_v[j]);
|
||||
}
|
||||
View *basis_vp = &d_basis_v[0];
|
||||
|
||||
// Queue n per-site kernels to the accelerator stream — no intermediate barriers.
|
||||
autoView(vec_v, vec, AcceleratorRead);
|
||||
for (int j = 0; j < n; ++j) {
|
||||
int jj = j;
|
||||
uint64_t oSites_ = oSites;
|
||||
accelerator_for(ss, oSites, nsimd, {
|
||||
auto x = coalescedRead(basis_vp[jj][ss]);
|
||||
auto y = coalescedRead(vec_v[ss]);
|
||||
coalescedWrite(all_ip_p[jj * oSites_ + ss], innerProduct(x, y));
|
||||
});
|
||||
}
|
||||
|
||||
// ONE sync after all n kernels
|
||||
accelerator_barrier();
|
||||
|
||||
// Copy all per-site results to host
|
||||
hostVector<inner_t> all_ip_h((uint64_t)n * oSites);
|
||||
acceleratorCopyFromDevice(all_ip_p, &all_ip_h[0], (uint64_t)n * oSites * sizeof(inner_t));
|
||||
|
||||
// Reduce on host: sum over oSites, then collapse SIMD lanes via Reduce(TensorRemove(...))
|
||||
// TensorRemove strips the iSinglet tensor wrapper to expose the SIMD scalar type.
|
||||
// Reduce sums all nsimd lanes and returns a plain scalar (RealD or ComplexD).
|
||||
std::vector<ComplexD> raw(n);
|
||||
for (int j = 0; j < n; ++j) {
|
||||
inner_t sum = Zero();
|
||||
for (uint64_t ss = 0; ss < oSites; ++ss)
|
||||
sum += all_ip_h[(uint64_t)j * oSites + ss];
|
||||
raw[j] = ComplexD(Reduce(TensorRemove(sum)));
|
||||
}
|
||||
grid->GlobalSumVector(&raw[0], n);
|
||||
for (int j = 0; j < n; ++j) c[j] = raw[j];
|
||||
|
||||
for (int j = 0; j < n; ++j) h_basis_v[j].ViewClose();
|
||||
}
|
||||
|
||||
void batchUpdate(Field &vec,
|
||||
const std::vector<Field> &basis,
|
||||
const std::vector<ComplexD> &c)
|
||||
{
|
||||
int n = (int)basis.size();
|
||||
if (n == 0) return;
|
||||
|
||||
typedef typename Field::vector_object vobj;
|
||||
typedef decltype(basis[0].View(AcceleratorRead)) View;
|
||||
|
||||
GridBase *grid = vec.Grid();
|
||||
uint64_t oSites = grid->oSites();
|
||||
uint64_t nsimd = grid->Nsimd();
|
||||
|
||||
// Split complex coefficients into real/imag double arrays on device.
|
||||
// Using doubles avoids potential ComplexD-device-code compatibility issues.
|
||||
hostVector<double> h_re(n), h_im(n);
|
||||
deviceVector<double> d_re(n), d_im(n);
|
||||
for (int k = 0; k < n; ++k) {
|
||||
h_re[k] = c[k].real();
|
||||
h_im[k] = c[k].imag();
|
||||
}
|
||||
acceleratorCopyToDevice(&h_re[0], &d_re[0], n * sizeof(double));
|
||||
acceleratorCopyToDevice(&h_im[0], &d_im[0], n * sizeof(double));
|
||||
double *re_p = &d_re[0];
|
||||
double *im_p = &d_im[0];
|
||||
|
||||
// Basis views
|
||||
hostVector<View> h_basis_v(n);
|
||||
deviceVector<View> d_basis_v(n);
|
||||
for (int k = 0; k < n; ++k) {
|
||||
h_basis_v[k] = basis[k].View(AcceleratorRead);
|
||||
acceleratorPut(d_basis_v[k], h_basis_v[k]);
|
||||
}
|
||||
View *basis_vp = &d_basis_v[0];
|
||||
|
||||
// Single kernel: vec[ss] -= sum_k (re[k] + i*im[k]) * basis[k][ss]
|
||||
autoView(vec_v, vec, AcceleratorWrite);
|
||||
accelerator_for(ss, oSites, nsimd, {
|
||||
auto v = coalescedRead(vec_v[ss]);
|
||||
for (int k = 0; k < n; ++k) {
|
||||
auto b = coalescedRead(basis_vp[k][ss]);
|
||||
v = v - re_p[k] * b - timesI(im_p[k] * b);
|
||||
}
|
||||
coalescedWrite(vec_v[ss], v);
|
||||
});
|
||||
|
||||
for (int k = 0; k < n; ++k) h_basis_v[k].ViewClose();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Full reorthogonalization using two-pass Classical Gram-Schmidt (CGS2).
|
||||
// Each pass calls batchInnerProducts (1 GPU sync) + batchUpdate (1 sync),
|
||||
// replacing the old 2n GPU syncs per pass from sequential MGS.
|
||||
// ------------------------------------------------------------------
|
||||
void reorthogonalize(Field &vec, const std::vector<Field> &basis)
|
||||
{
|
||||
if (basis.empty()) return;
|
||||
std::vector<ComplexD> c;
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
batchInnerProducts(vec, basis, c);
|
||||
batchUpdate(vec, basis, c);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Implicit restart: given the Nm-step bidiagonalization and its SVD,
|
||||
// compress to Nk steps via implicit QR shifts applied to B_k.
|
||||
//
|
||||
// The "shifts" are the Nm - Nk singular values we want to deflate
|
||||
// (those NOT in the desired set). We apply them as implicit QR steps
|
||||
// to the bidiagonal matrix, then update the lattice bases accordingly.
|
||||
//
|
||||
// After this call:
|
||||
// V[0..Nk], U[0..Nk-1], alpha[0..Nk-1], beta[0..Nk-1] are updated.
|
||||
// betaRestart ← new beta_Nk coupling for the next extension.
|
||||
// ------------------------------------------------------------------
|
||||
void implicitRestart(int k, int p,
|
||||
const Eigen::VectorXd &sigma,
|
||||
const Eigen::MatrixXd &X,
|
||||
const Eigen::MatrixXd &Y,
|
||||
const Eigen::VectorXi &order,
|
||||
RealD betaK,
|
||||
RealD &betaRestart)
|
||||
{
|
||||
// Thick restart (Baglama & Reichel, Sec. 2.2):
|
||||
//
|
||||
// Given B_k = X Sigma Y^T, define the new p-step basis by:
|
||||
// V^+_i = V_k * y_{order(i)} (right sing. vec. of B_k)
|
||||
// U^+_i = U_k * x_{order(i)} (left sing. vec. of B_k)
|
||||
//
|
||||
// Then A V^+_i = A V_k y_{order(i)} = U_k B_k y_{order(i)}
|
||||
// = sigma_{order(i)} U_k x_{order(i)} = sigma_{order(i)} U^+_i
|
||||
//
|
||||
// So B_p^+ = diag(sigma_{order(0)}, ..., sigma_{order(p-1)}) — DIAGONAL,
|
||||
// all internal betas are zero.
|
||||
//
|
||||
// The residual coupling comes from A^dag U_k = V_k B_k^T + betaK V[k] e_{k-1}^T:
|
||||
// A^dag U^+_{p-1} - sigma_{order(p-1)} V^+_{p-1}
|
||||
// = V_k (B_k^T x_{order(p-1)} - sigma_{order(p-1)} y_{order(p-1)})
|
||||
// + betaK * X(k-1, order(p-1)) * V[k]
|
||||
// = betaK * X(k-1, order(p-1)) * V[k] (since B_k^T x_j = sigma_j y_j)
|
||||
//
|
||||
// Therefore: betaRestart = |betaK * X(k-1, order(p-1))|
|
||||
// V[p] = sign(X(k-1, order(p-1))) * V[k]
|
||||
|
||||
// ---- Build new lattice vectors ----
|
||||
std::vector<Field> Vnew, Unew;
|
||||
Vnew.reserve(p + 1);
|
||||
Unew.reserve(p);
|
||||
|
||||
for (int i = 0; i < p; ++i) {
|
||||
int idx = order(i);
|
||||
Field vi(Grid); vi = Zero();
|
||||
for (int j = 0; j < k; ++j)
|
||||
vi = vi + Y(j, idx) * V[j];
|
||||
Vnew.push_back(vi);
|
||||
}
|
||||
|
||||
for (int i = 0; i < p; ++i) {
|
||||
int idx = order(i);
|
||||
Field ui(Grid); ui = Zero();
|
||||
for (int j = 0; j < k; ++j)
|
||||
ui = ui + X(j, idx) * U[j];
|
||||
Unew.push_back(ui);
|
||||
}
|
||||
|
||||
// New v_{p} (0-indexed: V[p]) = sign * V[k]
|
||||
// From A^dag U_k = V_k B_k^T + betaK V[k] e_{k-1}^T:
|
||||
// A^dag U^+_j - sigma_j V^+_j = betaK * X(k-1, order(j)) * V[k]
|
||||
// The last Ritz pair (j=p-1) defines betaRestart and the sign of V[p].
|
||||
// All p couplings (j=0..p-1) are stored in fvec so that buildFullB can
|
||||
// reconstruct the exact column p of U^dag A V after the next extension.
|
||||
RealD coeff = betaK * X(k - 1, order(p - 1));
|
||||
betaRestart = std::abs(coeff);
|
||||
RealD sgn = (coeff >= 0.0) ? 1.0 : -1.0;
|
||||
|
||||
fvec.resize(p);
|
||||
for (int j = 0; j < p; ++j)
|
||||
fvec[j] = betaK * X(k - 1, order(j)) * sgn;
|
||||
// fvec[p-1] == betaRestart by construction
|
||||
restart_col = p;
|
||||
|
||||
Field vp(Grid);
|
||||
if (betaRestart > 1.0e-14) {
|
||||
vp = sgn * V[k];
|
||||
} else {
|
||||
betaRestart = 0.0;
|
||||
vp = Zero();
|
||||
}
|
||||
Vnew.push_back(vp); // V[p]
|
||||
|
||||
// ---- New alpha, beta ----
|
||||
// B_p^+ is diagonal: alpha^+_i = sigma_{order(i)}, all internal beta = 0
|
||||
std::vector<RealD> alpha_new(p), beta_new(p);
|
||||
for (int i = 0; i < p; ++i) alpha_new[i] = sigma(order(i));
|
||||
for (int i = 0; i < p - 1; ++i) beta_new[i] = 0.0;
|
||||
beta_new[p - 1] = betaRestart;
|
||||
|
||||
// ---- Commit new state ----
|
||||
V = Vnew;
|
||||
U = Unew;
|
||||
alpha = alpha_new;
|
||||
beta = beta_new;
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "IRLBA restart: compressed to " << p << " steps,"
|
||||
<< " new beta_p = " << betaRestart << std::endl;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Extract the desired singular triplets into the public output vectors.
|
||||
// ------------------------------------------------------------------
|
||||
void extractTriplets(int m,
|
||||
const Eigen::VectorXd &sigma,
|
||||
const Eigen::MatrixXd &X,
|
||||
const Eigen::MatrixXd &Y,
|
||||
const Eigen::VectorXi &order,
|
||||
int nout)
|
||||
{
|
||||
singularValues.resize(nout);
|
||||
leftVectors.clear(); leftVectors.reserve(nout);
|
||||
rightVectors.clear(); rightVectors.reserve(nout);
|
||||
|
||||
for (int i = 0; i < nout; ++i) {
|
||||
int idx = order(i);
|
||||
singularValues[i] = sigma(idx);
|
||||
|
||||
// Left singular vector of A: svec_L = U_m * x_i
|
||||
Field svL(Grid); svL = Zero();
|
||||
for (int j = 0; j < m && j < (int)U.size(); ++j)
|
||||
svL = svL + X(j, idx) * U[j];
|
||||
leftVectors.push_back(svL);
|
||||
|
||||
// Right singular vector of A: svec_R = V_m * y_i
|
||||
Field svR(Grid); svR = Zero();
|
||||
for (int j = 0; j < m && j < (int)V.size(); ++j)
|
||||
svR = svR + Y(j, idx) * V[j];
|
||||
rightVectors.push_back(svR);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
#endif
|
||||
@@ -0,0 +1,931 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/iterative/ImplicitlyRestartedLanczos.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Chulwoo Jung <chulwoo@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_LANC_H
|
||||
#define GRID_LANC_H
|
||||
|
||||
#include <string.h> //memset
|
||||
|
||||
#ifdef USE_LAPACK
|
||||
#ifdef USE_MKL
|
||||
#include<mkl_lapack.h>
|
||||
#else
|
||||
void LAPACK_dstegr (char *jobz, char *range, int *n, double *d, double *e,
|
||||
double *vl, double *vu, int *il, int *iu, double *abstol,
|
||||
int *m, double *w, double *z, int *ldz, int *isuppz,
|
||||
double *work, int *lwork, int *iwork, int *liwork,
|
||||
int *info);
|
||||
//#include <lapacke/lapacke.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
//#include <Grid/algorithms/densematrix/DenseMatrix.h>
|
||||
|
||||
// eliminate temorary vector in calc()
|
||||
#define MEM_SAVE
|
||||
|
||||
namespace Grid
|
||||
{
|
||||
|
||||
struct Bisection
|
||||
{
|
||||
|
||||
#if 0
|
||||
static void get_eig2 (int row_num, std::vector < RealD > &ALPHA,
|
||||
std::vector < RealD > &BETA,
|
||||
std::vector < RealD > &eig)
|
||||
{
|
||||
int i, j;
|
||||
std::vector < RealD > evec1 (row_num + 3);
|
||||
std::vector < RealD > evec2 (row_num + 3);
|
||||
RealD eps2;
|
||||
ALPHA[1] = 0.;
|
||||
BETHA[1] = 0.;
|
||||
for (i = 0; i < row_num - 1; i++)
|
||||
{
|
||||
ALPHA[i + 1] = A[i * (row_num + 1)].real ();
|
||||
BETHA[i + 2] = A[i * (row_num + 1) + 1].real ();
|
||||
}
|
||||
ALPHA[row_num] = A[(row_num - 1) * (row_num + 1)].real ();
|
||||
bisec (ALPHA, BETHA, row_num, 1, row_num, 1e-10, 1e-10, evec1, eps2);
|
||||
bisec (ALPHA, BETHA, row_num, 1, row_num, 1e-16, 1e-16, evec2, eps2);
|
||||
|
||||
// Do we really need to sort here?
|
||||
int begin = 1;
|
||||
int end = row_num;
|
||||
int swapped = 1;
|
||||
while (swapped)
|
||||
{
|
||||
swapped = 0;
|
||||
for (i = begin; i < end; i++)
|
||||
{
|
||||
if (mag (evec2[i]) > mag (evec2[i + 1]))
|
||||
{
|
||||
swap (evec2 + i, evec2 + i + 1);
|
||||
swapped = 1;
|
||||
}
|
||||
}
|
||||
end--;
|
||||
for (i = end - 1; i >= begin; i--)
|
||||
{
|
||||
if (mag (evec2[i]) > mag (evec2[i + 1]))
|
||||
{
|
||||
swap (evec2 + i, evec2 + i + 1);
|
||||
swapped = 1;
|
||||
}
|
||||
}
|
||||
begin++;
|
||||
}
|
||||
|
||||
for (i = 0; i < row_num; i++)
|
||||
{
|
||||
for (j = 0; j < row_num; j++)
|
||||
{
|
||||
if (i == j)
|
||||
H[i * row_num + j] = evec2[i + 1];
|
||||
else
|
||||
H[i * row_num + j] = 0.;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
static void bisec (std::vector < RealD > &c,
|
||||
std::vector < RealD > &b,
|
||||
int n,
|
||||
int m1,
|
||||
int m2,
|
||||
RealD eps1,
|
||||
RealD relfeh, std::vector < RealD > &x, RealD & eps2)
|
||||
{
|
||||
std::vector < RealD > wu (n + 2);
|
||||
|
||||
RealD h, q, x1, xu, x0, xmin, xmax;
|
||||
int i, a, k;
|
||||
|
||||
b[1] = 0.0;
|
||||
xmin = c[n] - fabs (b[n]);
|
||||
xmax = c[n] + fabs (b[n]);
|
||||
for (i = 1; i < n; i++)
|
||||
{
|
||||
h = fabs (b[i]) + fabs (b[i + 1]);
|
||||
if (c[i] + h > xmax)
|
||||
xmax = c[i] + h;
|
||||
if (c[i] - h < xmin)
|
||||
xmin = c[i] - h;
|
||||
}
|
||||
xmax *= 2.;
|
||||
|
||||
eps2 = relfeh * ((xmin + xmax) > 0.0 ? xmax : -xmin);
|
||||
if (eps1 <= 0.0)
|
||||
eps1 = eps2;
|
||||
eps2 = 0.5 * eps1 + 7.0 * (eps2);
|
||||
x0 = xmax;
|
||||
for (i = m1; i <= m2; i++)
|
||||
{
|
||||
x[i] = xmax;
|
||||
wu[i] = xmin;
|
||||
}
|
||||
|
||||
for (k = m2; k >= m1; k--)
|
||||
{
|
||||
xu = xmin;
|
||||
i = k;
|
||||
do
|
||||
{
|
||||
if (xu < wu[i])
|
||||
{
|
||||
xu = wu[i];
|
||||
i = m1 - 1;
|
||||
}
|
||||
i--;
|
||||
}
|
||||
while (i >= m1);
|
||||
if (x0 > x[k])
|
||||
x0 = x[k];
|
||||
while ((x0 - xu) > 2 * relfeh * (fabs (xu) + fabs (x0)) + eps1)
|
||||
{
|
||||
x1 = (xu + x0) / 2;
|
||||
|
||||
a = 0;
|
||||
q = 1.0;
|
||||
for (i = 1; i <= n; i++)
|
||||
{
|
||||
q =
|
||||
c[i] - x1 -
|
||||
((q != 0.0) ? b[i] * b[i] / q : fabs (b[i]) / relfeh);
|
||||
if (q < 0)
|
||||
a++;
|
||||
}
|
||||
// printf("x1=%0.14e a=%d\n",x1,a);
|
||||
if (a < k)
|
||||
{
|
||||
if (a < m1)
|
||||
{
|
||||
xu = x1;
|
||||
wu[m1] = x1;
|
||||
}
|
||||
else
|
||||
{
|
||||
xu = x1;
|
||||
wu[a + 1] = x1;
|
||||
if (x[a] > x1)
|
||||
x[a] = x1;
|
||||
}
|
||||
}
|
||||
else
|
||||
x0 = x1;
|
||||
}
|
||||
printf ("x0=%0.14e xu=%0.14e k=%d\n", x0, xu, k);
|
||||
x[k] = (x0 + xu) / 2;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// Implicitly restarted lanczos
|
||||
/////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
template < class Field > class SimpleLanczos
|
||||
{
|
||||
|
||||
const RealD small = 1.0e-16;
|
||||
public:
|
||||
int lock;
|
||||
int get;
|
||||
int Niter;
|
||||
int converged;
|
||||
|
||||
int Nstop; // Number of evecs checked for convergence
|
||||
int Nk; // Number of converged sought
|
||||
int Np; // Np -- Number of spare vecs in kryloc space
|
||||
int Nm; // Nm -- total number of vectors
|
||||
|
||||
|
||||
RealD OrthoTime;
|
||||
|
||||
RealD eresid;
|
||||
|
||||
// SortEigen < Field > _sort;
|
||||
|
||||
LinearFunction < Field > &_Linop;
|
||||
|
||||
// OperatorFunction < Field > &_poly;
|
||||
|
||||
/////////////////////////
|
||||
// Constructor
|
||||
/////////////////////////
|
||||
void init (void)
|
||||
{
|
||||
};
|
||||
// void Abort (int ff, std::vector < RealD > &evals, DenseVector < Denstd::vector < RealD > >&evecs);
|
||||
|
||||
SimpleLanczos (LinearFunction < Field > &Linop, // op
|
||||
// OperatorFunction < Field > &poly, // polynmial
|
||||
int _Nstop, // sought vecs
|
||||
int _Nk, // sought vecs
|
||||
int _Nm, // spare vecs
|
||||
RealD _eresid, // resid in lmdue deficit
|
||||
int _Niter): // Max iterations
|
||||
|
||||
_Linop (Linop),
|
||||
// _poly (poly),
|
||||
Nstop (_Nstop), Nk (_Nk), Nm (_Nm), eresid (_eresid), Niter (_Niter)
|
||||
{
|
||||
Np = Nm - Nk;
|
||||
assert (Np > 0);
|
||||
};
|
||||
|
||||
/////////////////////////
|
||||
// Sanity checked this routine (step) against Saad.
|
||||
/////////////////////////
|
||||
void RitzMatrix (std::vector < Field > &evec, int k)
|
||||
{
|
||||
|
||||
if (1)
|
||||
return;
|
||||
|
||||
GridBase *grid = evec[0].Grid();
|
||||
Field w (grid);
|
||||
std::cout << GridLogMessage << "RitzMatrix " << std::endl;
|
||||
for (int i = 0; i < k; i++)
|
||||
{
|
||||
_Linop(evec[i], w);
|
||||
// _poly(_Linop,evec[i],w);
|
||||
std::cout << GridLogMessage << "[" << i << "] ";
|
||||
for (int j = 0; j < k; j++)
|
||||
{
|
||||
ComplexD in = innerProduct (evec[j], w);
|
||||
if (fabs ((double) i - j) > 1)
|
||||
{
|
||||
if (abs (in) > 1.0e-9)
|
||||
{
|
||||
std::cout << GridLogMessage << "oops" << std::endl;
|
||||
abort ();
|
||||
}
|
||||
else
|
||||
std::cout << GridLogMessage << " 0 ";
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << GridLogMessage << " " << in << " ";
|
||||
}
|
||||
}
|
||||
std::cout << GridLogMessage << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void step (std::vector < RealD > &lmd,
|
||||
std::vector < RealD > &lme,
|
||||
Field & last, Field & current, Field & next, uint64_t k)
|
||||
{
|
||||
if (lmd.size () <= k)
|
||||
lmd.resize (k + Nm);
|
||||
if (lme.size () <= k)
|
||||
lme.resize (k + Nm);
|
||||
|
||||
|
||||
// _poly(_Linop,current,next ); // 3. wk:=Avk−βkv_{k−1}
|
||||
_Linop(current, next); // 3. wk:=Avk−βkv_{k−1}
|
||||
if (k > 0)
|
||||
{
|
||||
next -= lme[k - 1] * last;
|
||||
}
|
||||
// std::cout<<GridLogMessage << "<last|next>" << innerProduct(last,next) <<std::endl;
|
||||
|
||||
ComplexD zalph = innerProduct (current, next); // 4. αk:=(wk,vk)
|
||||
RealD alph = real (zalph);
|
||||
|
||||
next = next - alph * current; // 5. wk:=wk−αkvk
|
||||
// std::cout<<GridLogMessage << "<current|next>" << innerProduct(current,next) <<std::endl;
|
||||
|
||||
RealD beta = normalise (next); // 6. βk+1 := ∥wk∥2. If βk+1 = 0 then Stop
|
||||
// 7. vk+1 := wk/βk+1
|
||||
// norm=beta;
|
||||
|
||||
int interval = Nm / 100 + 1;
|
||||
if ((k % interval) == 0)
|
||||
std::
|
||||
cout << GridLogMessage << k << " : alpha = " << zalph << " beta " <<
|
||||
beta << std::endl;
|
||||
const RealD tiny = 1.0e-20;
|
||||
if (beta < tiny)
|
||||
{
|
||||
std::cout << GridLogMessage << " beta is tiny " << beta << std::
|
||||
endl;
|
||||
}
|
||||
lmd[k] = alph;
|
||||
lme[k] = beta;
|
||||
|
||||
}
|
||||
|
||||
void qr_decomp (std::vector < RealD > &lmd,
|
||||
std::vector < RealD > &lme,
|
||||
int Nk,
|
||||
int Nm,
|
||||
std::vector < RealD > &Qt, RealD Dsh, int kmin, int kmax)
|
||||
{
|
||||
int k = kmin - 1;
|
||||
RealD x;
|
||||
|
||||
RealD Fden = 1.0 / hypot (lmd[k] - Dsh, lme[k]);
|
||||
RealD c = (lmd[k] - Dsh) * Fden;
|
||||
RealD s = -lme[k] * Fden;
|
||||
|
||||
RealD tmpa1 = lmd[k];
|
||||
RealD tmpa2 = lmd[k + 1];
|
||||
RealD tmpb = lme[k];
|
||||
|
||||
lmd[k] = c * c * tmpa1 + s * s * tmpa2 - 2.0 * c * s * tmpb;
|
||||
lmd[k + 1] = s * s * tmpa1 + c * c * tmpa2 + 2.0 * c * s * tmpb;
|
||||
lme[k] = c * s * (tmpa1 - tmpa2) + (c * c - s * s) * tmpb;
|
||||
x = -s * lme[k + 1];
|
||||
lme[k + 1] = c * lme[k + 1];
|
||||
|
||||
for (int i = 0; i < Nk; ++i)
|
||||
{
|
||||
RealD Qtmp1 = Qt[i + Nm * k];
|
||||
RealD Qtmp2 = Qt[i + Nm * (k + 1)];
|
||||
Qt[i + Nm * k] = c * Qtmp1 - s * Qtmp2;
|
||||
Qt[i + Nm * (k + 1)] = s * Qtmp1 + c * Qtmp2;
|
||||
}
|
||||
|
||||
// Givens transformations
|
||||
for (int k = kmin; k < kmax - 1; ++k)
|
||||
{
|
||||
|
||||
RealD Fden = 1.0 / hypot (x, lme[k - 1]);
|
||||
RealD c = lme[k - 1] * Fden;
|
||||
RealD s = -x * Fden;
|
||||
|
||||
RealD tmpa1 = lmd[k];
|
||||
RealD tmpa2 = lmd[k + 1];
|
||||
RealD tmpb = lme[k];
|
||||
|
||||
lmd[k] = c * c * tmpa1 + s * s * tmpa2 - 2.0 * c * s * tmpb;
|
||||
lmd[k + 1] = s * s * tmpa1 + c * c * tmpa2 + 2.0 * c * s * tmpb;
|
||||
lme[k] = c * s * (tmpa1 - tmpa2) + (c * c - s * s) * tmpb;
|
||||
lme[k - 1] = c * lme[k - 1] - s * x;
|
||||
|
||||
if (k != kmax - 2)
|
||||
{
|
||||
x = -s * lme[k + 1];
|
||||
lme[k + 1] = c * lme[k + 1];
|
||||
}
|
||||
|
||||
for (int i = 0; i < Nk; ++i)
|
||||
{
|
||||
RealD Qtmp1 = Qt[i + Nm * k];
|
||||
RealD Qtmp2 = Qt[i + Nm * (k + 1)];
|
||||
Qt[i + Nm * k] = c * Qtmp1 - s * Qtmp2;
|
||||
Qt[i + Nm * (k + 1)] = s * Qtmp1 + c * Qtmp2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if 0
|
||||
#ifdef USE_LAPACK
|
||||
#ifdef USE_MKL
|
||||
#define LAPACK_INT MKL_INT
|
||||
#else
|
||||
#define LAPACK_INT long long
|
||||
#endif
|
||||
void diagonalize_lapack (std::vector < RealD > &lmd, std::vector < RealD > &lme, int N1, // all
|
||||
int N2, // get
|
||||
GridBase * grid)
|
||||
{
|
||||
const int size = Nm;
|
||||
LAPACK_INT NN = N1;
|
||||
double evals_tmp[NN];
|
||||
double DD[NN];
|
||||
double EE[NN];
|
||||
for (int i = 0; i < NN; i++)
|
||||
for (int j = i - 1; j <= i + 1; j++)
|
||||
if (j < NN && j >= 0)
|
||||
{
|
||||
if (i == j)
|
||||
DD[i] = lmd[i];
|
||||
if (i == j)
|
||||
evals_tmp[i] = lmd[i];
|
||||
if (j == (i - 1))
|
||||
EE[j] = lme[j];
|
||||
}
|
||||
LAPACK_INT evals_found;
|
||||
LAPACK_INT lwork =
|
||||
((18 * NN) >
|
||||
(1 + 4 * NN + NN * NN) ? (18 * NN) : (1 + 4 * NN + NN * NN));
|
||||
LAPACK_INT liwork = 3 + NN * 10;
|
||||
LAPACK_INT iwork[liwork];
|
||||
double work[lwork];
|
||||
LAPACK_INT isuppz[2 * NN];
|
||||
char jobz = 'N'; // calculate evals only
|
||||
char range = 'I'; // calculate il-th to iu-th evals
|
||||
// char range = 'A'; // calculate all evals
|
||||
char uplo = 'U'; // refer to upper half of original matrix
|
||||
char compz = 'I'; // Compute eigenvectors of tridiagonal matrix
|
||||
int ifail[NN];
|
||||
LAPACK_INT info;
|
||||
// int total = QMP_get_number_of_nodes();
|
||||
// int node = QMP_get_node_number();
|
||||
// GridBase *grid = evec[0]._grid;
|
||||
int total = grid->_Nprocessors;
|
||||
int node = grid->_processor;
|
||||
int interval = (NN / total) + 1;
|
||||
double vl = 0.0, vu = 0.0;
|
||||
LAPACK_INT il = interval * node + 1, iu = interval * (node + 1);
|
||||
if (iu > NN)
|
||||
iu = NN;
|
||||
double tol = 0.0;
|
||||
if (1)
|
||||
{
|
||||
memset (evals_tmp, 0, sizeof (double) * NN);
|
||||
if (il <= NN)
|
||||
{
|
||||
printf ("total=%d node=%d il=%d iu=%d\n", total, node, il, iu);
|
||||
#ifdef USE_MKL
|
||||
dstegr (&jobz, &range, &NN,
|
||||
#else
|
||||
LAPACK_dstegr (&jobz, &range, &NN,
|
||||
#endif
|
||||
(double *) DD, (double *) EE, &vl, &vu, &il, &iu, // these four are ignored if second parameteris 'A'
|
||||
&tol, // tolerance
|
||||
&evals_found, evals_tmp, (double *) NULL, &NN,
|
||||
isuppz, work, &lwork, iwork, &liwork, &info);
|
||||
for (int i = iu - 1; i >= il - 1; i--)
|
||||
{
|
||||
printf ("node=%d evals_found=%d evals_tmp[%d] = %g\n", node,
|
||||
evals_found, i - (il - 1), evals_tmp[i - (il - 1)]);
|
||||
evals_tmp[i] = evals_tmp[i - (il - 1)];
|
||||
if (il > 1)
|
||||
evals_tmp[i - (il - 1)] = 0.;
|
||||
}
|
||||
}
|
||||
{
|
||||
grid->GlobalSumVector (evals_tmp, NN);
|
||||
}
|
||||
}
|
||||
// cheating a bit. It is better to sort instead of just reversing it, but the document of the routine says evals are sorted in increasing order. qr gives evals in decreasing order.
|
||||
}
|
||||
#undef LAPACK_INT
|
||||
#endif
|
||||
|
||||
|
||||
void diagonalize (std::vector < RealD > &lmd,
|
||||
std::vector < RealD > &lme,
|
||||
int N2, int N1, GridBase * grid)
|
||||
{
|
||||
|
||||
#ifdef USE_LAPACK
|
||||
const int check_lapack = 0; // just use lapack if 0, check against lapack if 1
|
||||
|
||||
if (!check_lapack)
|
||||
return diagonalize_lapack (lmd, lme, N2, N1, grid);
|
||||
|
||||
// diagonalize_lapack(lmd2,lme2,Nm2,Nm,Qt,grid);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
static RealD normalise (Field & v)
|
||||
{
|
||||
RealD nn = norm2 (v);
|
||||
nn = sqrt (nn);
|
||||
v = v * (1.0 / nn);
|
||||
return nn;
|
||||
}
|
||||
|
||||
void orthogonalize (Field & w, std::vector < Field > &evec, int k)
|
||||
{
|
||||
double t0 = -usecond () / 1e6;
|
||||
typedef typename Field::scalar_type MyComplex;
|
||||
MyComplex ip;
|
||||
|
||||
if (0)
|
||||
{
|
||||
for (int j = 0; j < k; ++j)
|
||||
{
|
||||
normalise (evec[j]);
|
||||
for (int i = 0; i < j; i++)
|
||||
{
|
||||
ip = innerProduct (evec[i], evec[j]); // are the evecs normalised? ; this assumes so.
|
||||
evec[j] = evec[j] - ip * evec[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int j = 0; j < k; ++j)
|
||||
{
|
||||
ip = innerProduct (evec[j], w); // are the evecs normalised? ; this assumes so.
|
||||
w = w - ip * evec[j];
|
||||
}
|
||||
normalise (w);
|
||||
t0 += usecond () / 1e6;
|
||||
OrthoTime += t0;
|
||||
}
|
||||
|
||||
void setUnit_Qt (int Nm, std::vector < RealD > &Qt)
|
||||
{
|
||||
for (int i = 0; i < Qt.size (); ++i)
|
||||
Qt[i] = 0.0;
|
||||
for (int k = 0; k < Nm; ++k)
|
||||
Qt[k + k * Nm] = 1.0;
|
||||
}
|
||||
|
||||
|
||||
void calc (std::vector < RealD > &eval, const Field & src, int &Nconv)
|
||||
{
|
||||
|
||||
GridBase *grid = src.Grid();
|
||||
// assert(grid == src._grid);
|
||||
|
||||
std::
|
||||
cout << GridLogMessage << " -- Nk = " << Nk << " Np = " << Np << std::
|
||||
endl;
|
||||
std::cout << GridLogMessage << " -- Nm = " << Nm << std::endl;
|
||||
std::cout << GridLogMessage << " -- size of eval = " << eval.
|
||||
size () << std::endl;
|
||||
|
||||
// assert(c.size() && Nm == eval.size());
|
||||
|
||||
std::vector < RealD > lme (Nm);
|
||||
std::vector < RealD > lmd (Nm);
|
||||
|
||||
|
||||
Field current (grid);
|
||||
Field last (grid);
|
||||
Field next (grid);
|
||||
|
||||
Nconv = 0;
|
||||
|
||||
RealD beta_k;
|
||||
|
||||
// Set initial vector
|
||||
// (uniform vector) Why not src??
|
||||
// evec[0] = 1.0;
|
||||
current = src;
|
||||
std::cout << GridLogMessage << "norm2(src)= " << norm2 (src) << std::
|
||||
endl;
|
||||
normalise (current);
|
||||
std::
|
||||
cout << GridLogMessage << "norm2(evec[0])= " << norm2 (current) <<
|
||||
std::endl;
|
||||
|
||||
// Initial Nk steps
|
||||
OrthoTime = 0.;
|
||||
double t0 = usecond () / 1e6;
|
||||
RealD norm; // sqrt norm of last vector
|
||||
|
||||
uint64_t iter = 0;
|
||||
|
||||
bool initted = false;
|
||||
std::vector < RealD > low (Nstop * 10);
|
||||
std::vector < RealD > high (Nstop * 10);
|
||||
RealD cont = 0.;
|
||||
while (1) {
|
||||
cont = 0.;
|
||||
std::vector < RealD > lme2 (Nm);
|
||||
std::vector < RealD > lmd2 (Nm);
|
||||
for (uint64_t k = 0; k < Nm; ++k, iter++) {
|
||||
step (lmd, lme, last, current, next, iter);
|
||||
last = current;
|
||||
current = next;
|
||||
}
|
||||
double t1 = usecond () / 1e6;
|
||||
std::cout << GridLogMessage << "IRL::Initial steps: " << t1 -
|
||||
t0 << "seconds" << std::endl;
|
||||
t0 = t1;
|
||||
std::
|
||||
cout << GridLogMessage << "IRL::Initial steps:OrthoTime " <<
|
||||
OrthoTime << "seconds" << std::endl;
|
||||
|
||||
// getting eigenvalues
|
||||
lmd2.resize (iter + 2);
|
||||
lme2.resize (iter + 2);
|
||||
for (uint64_t k = 0; k < iter; ++k) {
|
||||
lmd2[k + 1] = lmd[k];
|
||||
lme2[k + 2] = lme[k];
|
||||
}
|
||||
t1 = usecond () / 1e6;
|
||||
std::cout << GridLogMessage << "IRL:: copy: " << t1 -
|
||||
t0 << "seconds" << std::endl;
|
||||
t0 = t1;
|
||||
{
|
||||
int total = grid->_Nprocessors;
|
||||
int node = grid->_processor;
|
||||
int interval = (Nstop / total) + 1;
|
||||
int iu = (iter + 1) - (interval * node + 1);
|
||||
int il = (iter + 1) - (interval * (node + 1));
|
||||
std::vector < RealD > eval2 (iter + 3);
|
||||
RealD eps2;
|
||||
Bisection::bisec (lmd2, lme2, iter, il, iu, 1e-16, 1e-10, eval2,
|
||||
eps2);
|
||||
// diagonalize(eval2,lme2,iter,Nk,grid);
|
||||
RealD diff = 0.;
|
||||
for (int i = il; i <= iu; i++) {
|
||||
if (initted)
|
||||
diff =
|
||||
fabs (eval2[i] - high[iu-i]) / (fabs (eval2[i]) +
|
||||
fabs (high[iu-i]));
|
||||
if (initted && (diff > eresid))
|
||||
cont = 1.;
|
||||
if (initted)
|
||||
printf ("eval[%d]=%0.14e %0.14e, %0.14e\n", i, eval2[i],
|
||||
high[iu-i], diff);
|
||||
high[iu-i] = eval2[i];
|
||||
}
|
||||
il = (interval * node + 1);
|
||||
iu = (interval * (node + 1));
|
||||
Bisection::bisec (lmd2, lme2, iter, il, iu, 1e-16, 1e-10, eval2,
|
||||
eps2);
|
||||
for (int i = il; i <= iu; i++) {
|
||||
if (initted)
|
||||
diff =
|
||||
fabs (eval2[i] - low[i]) / (fabs (eval2[i]) +
|
||||
fabs (low[i]));
|
||||
if (initted && (diff > eresid))
|
||||
cont = 1.;
|
||||
if (initted)
|
||||
printf ("eval[%d]=%0.14e %0.14e, %0.14e\n", i, eval2[i],
|
||||
low[i], diff);
|
||||
low[i] = eval2[i];
|
||||
}
|
||||
t1 = usecond () / 1e6;
|
||||
std::cout << GridLogMessage << "IRL:: diagonalize: " << t1 -
|
||||
t0 << "seconds" << std::endl;
|
||||
t0 = t1;
|
||||
}
|
||||
|
||||
for (uint64_t k = 0; k < Nk; ++k) {
|
||||
// eval[k] = eval2[k];
|
||||
}
|
||||
if (initted)
|
||||
{
|
||||
grid->GlobalSumVector (&cont, 1);
|
||||
if (cont < 1.) return;
|
||||
}
|
||||
initted = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#if 0
|
||||
|
||||
/**
|
||||
There is some matrix Q such that for any vector y
|
||||
Q.e_1 = y and Q is unitary.
|
||||
**/
|
||||
template < class T >
|
||||
static T orthQ (DenseMatrix < T > &Q, std::vector < T > y)
|
||||
{
|
||||
int N = y.size (); //Matrix Size
|
||||
Fill (Q, 0.0);
|
||||
T tau;
|
||||
for (int i = 0; i < N; i++)
|
||||
{
|
||||
Q[i][0] = y[i];
|
||||
}
|
||||
T sig = conj (y[0]) * y[0];
|
||||
T tau0 = fabs (sqrt (sig));
|
||||
|
||||
for (int j = 1; j < N; j++)
|
||||
{
|
||||
sig += conj (y[j]) * y[j];
|
||||
tau = abs (sqrt (sig));
|
||||
|
||||
if (abs (tau0) > 0.0)
|
||||
{
|
||||
|
||||
T gam = conj ((y[j] / tau) / tau0);
|
||||
for (int k = 0; k <= j - 1; k++)
|
||||
{
|
||||
Q[k][j] = -gam * y[k];
|
||||
}
|
||||
Q[j][j] = tau0 / tau;
|
||||
}
|
||||
else
|
||||
{
|
||||
Q[j - 1][j] = 1.0;
|
||||
}
|
||||
tau0 = tau;
|
||||
}
|
||||
return tau;
|
||||
}
|
||||
|
||||
/**
|
||||
There is some matrix Q such that for any vector y
|
||||
Q.e_k = y and Q is unitary.
|
||||
**/
|
||||
template < class T >
|
||||
static T orthU (DenseMatrix < T > &Q, std::vector < T > y)
|
||||
{
|
||||
T tau = orthQ (Q, y);
|
||||
SL (Q);
|
||||
return tau;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
Wind up with a matrix with the first con rows untouched
|
||||
|
||||
say con = 2
|
||||
Q is such that Qdag H Q has {x, x, val, 0, 0, 0, 0, ...} as 1st colum
|
||||
and the matrix is upper hessenberg
|
||||
and with f and Q appropriately modidied with Q is the arnoldi factorization
|
||||
|
||||
**/
|
||||
|
||||
template < class T > static void Lock (DenseMatrix < T > &H, ///Hess mtx
|
||||
DenseMatrix < T > &Q, ///Lock Transform
|
||||
T val, ///value to be locked
|
||||
int con, ///number already locked
|
||||
RealD small, int dfg, bool herm)
|
||||
{
|
||||
//ForceTridiagonal(H);
|
||||
|
||||
int M = H.dim;
|
||||
DenseVector < T > vec;
|
||||
Resize (vec, M - con);
|
||||
|
||||
DenseMatrix < T > AH;
|
||||
Resize (AH, M - con, M - con);
|
||||
AH = GetSubMtx (H, con, M, con, M);
|
||||
|
||||
DenseMatrix < T > QQ;
|
||||
Resize (QQ, M - con, M - con);
|
||||
|
||||
Unity (Q);
|
||||
Unity (QQ);
|
||||
|
||||
DenseVector < T > evals;
|
||||
Resize (evals, M - con);
|
||||
DenseMatrix < T > evecs;
|
||||
Resize (evecs, M - con, M - con);
|
||||
|
||||
Wilkinson < T > (AH, evals, evecs, small);
|
||||
|
||||
int k = 0;
|
||||
RealD cold = abs (val - evals[k]);
|
||||
for (int i = 1; i < M - con; i++)
|
||||
{
|
||||
RealD cnew = abs (val - evals[i]);
|
||||
if (cnew < cold)
|
||||
{
|
||||
k = i;
|
||||
cold = cnew;
|
||||
}
|
||||
}
|
||||
vec = evecs[k];
|
||||
|
||||
ComplexD tau;
|
||||
orthQ (QQ, vec);
|
||||
//orthQM(QQ,AH,vec);
|
||||
|
||||
AH = Hermitian (QQ) * AH;
|
||||
AH = AH * QQ;
|
||||
|
||||
for (int i = con; i < M; i++)
|
||||
{
|
||||
for (int j = con; j < M; j++)
|
||||
{
|
||||
Q[i][j] = QQ[i - con][j - con];
|
||||
H[i][j] = AH[i - con][j - con];
|
||||
}
|
||||
}
|
||||
|
||||
for (int j = M - 1; j > con + 2; j--)
|
||||
{
|
||||
|
||||
DenseMatrix < T > U;
|
||||
Resize (U, j - 1 - con, j - 1 - con);
|
||||
DenseVector < T > z;
|
||||
Resize (z, j - 1 - con);
|
||||
T nm = norm (z);
|
||||
for (int k = con + 0; k < j - 1; k++)
|
||||
{
|
||||
z[k - con] = conj (H (j, k + 1));
|
||||
}
|
||||
normalise (z);
|
||||
|
||||
RealD tmp = 0;
|
||||
for (int i = 0; i < z.size () - 1; i++)
|
||||
{
|
||||
tmp = tmp + abs (z[i]);
|
||||
}
|
||||
|
||||
if (tmp < small / ((RealD) z.size () - 1.0))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
tau = orthU (U, z);
|
||||
|
||||
DenseMatrix < T > Hb;
|
||||
Resize (Hb, j - 1 - con, M);
|
||||
|
||||
for (int a = 0; a < M; a++)
|
||||
{
|
||||
for (int b = 0; b < j - 1 - con; b++)
|
||||
{
|
||||
T sum = 0;
|
||||
for (int c = 0; c < j - 1 - con; c++)
|
||||
{
|
||||
sum += H[a][con + 1 + c] * U[c][b];
|
||||
} //sum += H(a,con+1+c)*U(c,b);}
|
||||
Hb[b][a] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
for (int k = con + 1; k < j; k++)
|
||||
{
|
||||
for (int l = 0; l < M; l++)
|
||||
{
|
||||
H[l][k] = Hb[k - 1 - con][l];
|
||||
}
|
||||
} //H(Hb[k-1-con][l] , l,k);}}
|
||||
|
||||
DenseMatrix < T > Qb;
|
||||
Resize (Qb, M, M);
|
||||
|
||||
for (int a = 0; a < M; a++)
|
||||
{
|
||||
for (int b = 0; b < j - 1 - con; b++)
|
||||
{
|
||||
T sum = 0;
|
||||
for (int c = 0; c < j - 1 - con; c++)
|
||||
{
|
||||
sum += Q[a][con + 1 + c] * U[c][b];
|
||||
} //sum += Q(a,con+1+c)*U(c,b);}
|
||||
Qb[b][a] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
for (int k = con + 1; k < j; k++)
|
||||
{
|
||||
for (int l = 0; l < M; l++)
|
||||
{
|
||||
Q[l][k] = Qb[k - 1 - con][l];
|
||||
}
|
||||
} //Q(Qb[k-1-con][l] , l,k);}}
|
||||
|
||||
DenseMatrix < T > Hc;
|
||||
Resize (Hc, M, M);
|
||||
|
||||
for (int a = 0; a < j - 1 - con; a++)
|
||||
{
|
||||
for (int b = 0; b < M; b++)
|
||||
{
|
||||
T sum = 0;
|
||||
for (int c = 0; c < j - 1 - con; c++)
|
||||
{
|
||||
sum += conj (U[c][a]) * H[con + 1 + c][b];
|
||||
} //sum += conj( U(c,a) )*H(con+1+c,b);}
|
||||
Hc[b][a] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
for (int k = 0; k < M; k++)
|
||||
{
|
||||
for (int l = con + 1; l < j; l++)
|
||||
{
|
||||
H[l][k] = Hc[k][l - 1 - con];
|
||||
}
|
||||
} //H(Hc[k][l-1-con] , l,k);}}
|
||||
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,124 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/iterative/SplitGridBlockKrylovSchur.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Peter Boyle <paboyle@ph.ed.ac.uk>
|
||||
Author: Chulwoo Jung <chulwoo@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_SPLIT_BLOCK_KRYLOV_SCHUR_H
|
||||
#define GRID_SPLIT_BLOCK_KRYLOV_SCHUR_H
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
/**
|
||||
* Block Krylov-Schur eigensolver with Split-Grid batched operator application.
|
||||
*
|
||||
* Derives from BlockKrylovSchur<Field> and overrides only the operator
|
||||
* application: instead of calling Linop.Op() once per vector, mrhs vectors
|
||||
* are packed onto a smaller split grid with Grid_split, the polynomial-
|
||||
* filtered operator poly(SLinop) is applied once to the combined field, and
|
||||
* the results are unpacked with Grid_unsplit. All other algorithmic logic
|
||||
* (Arnoldi orthogonalisation, Schur restart, convergence test, etc.) is
|
||||
* inherited unchanged from the base class.
|
||||
*
|
||||
* Constructor extras (beyond BlockKrylovSchur)
|
||||
* -------------------------------------------
|
||||
* SLinop : split-grid linear operator used inside poly
|
||||
* poly : polynomial filter OperatorFunction applied on the split grid
|
||||
* SGrid : split-grid GridBase (mrhs fields packed here)
|
||||
* mrhs : RHS batched per split-grid call; Nblock must be divisible by mrhs
|
||||
*
|
||||
* Notes
|
||||
* -----
|
||||
* - The Rayleigh quotient H is built from poly(A), so its Ritz values are
|
||||
* eigenvalues of poly(A). Convergence is assessed against the full-grid
|
||||
* Linop (inherited from base), giving true A-eigenvalues.
|
||||
* - Grid_ (inherited) is the full grid; SGrid is the split grid.
|
||||
*/
|
||||
template<class Field>
|
||||
class SplitGridBlockKrylovSchur : public BlockKrylovSchur<Field> {
|
||||
|
||||
using Base = BlockKrylovSchur<Field>;
|
||||
|
||||
// Bring protected base members into scope
|
||||
using Base::Nblock;
|
||||
using Base::Grid_;
|
||||
using Base::basis;
|
||||
|
||||
// Split-grid extras
|
||||
LinearOperatorBase<Field>& SLinop;
|
||||
OperatorFunction<Field>& poly;
|
||||
GridBase* SGrid;
|
||||
int mrhs;
|
||||
|
||||
public:
|
||||
|
||||
SplitGridBlockKrylovSchur(LinearOperatorBase<Field>& _Linop,
|
||||
LinearOperatorBase<Field>& _SLinop,
|
||||
OperatorFunction<Field>& _poly,
|
||||
GridBase* _FGrid,
|
||||
GridBase* _SGrid,
|
||||
int _mrhs,
|
||||
RealD _Tolerance,
|
||||
RitzFilter _rf = EvalReSmall)
|
||||
: Base(_Linop, _FGrid, _Tolerance, _rf),
|
||||
SLinop(_SLinop), poly(_poly), SGrid(_SGrid), mrhs(_mrhs)
|
||||
{}
|
||||
|
||||
protected:
|
||||
|
||||
// Validate mrhs divisibility before the Arnoldi loop starts
|
||||
void preRun() override
|
||||
{
|
||||
assert(Nblock % mrhs == 0 && "Nblock must be divisible by mrhs");
|
||||
}
|
||||
|
||||
// Apply poly(A) to basis[kBase .. kBase+Nblock-1] via Grid_split / Grid_unsplit,
|
||||
// batching mrhs vectors per split-grid call.
|
||||
void applyBlock(std::vector<Field>& W, int kBase) override
|
||||
{
|
||||
std::vector<Field> in(mrhs, Field(Grid_));
|
||||
Field s_in(SGrid);
|
||||
Field s_out(SGrid);
|
||||
|
||||
int k_start = 0;
|
||||
while (k_start < Nblock) {
|
||||
for (int u = 0; u < mrhs; u++)
|
||||
in[u] = basis[kBase + k_start + u];
|
||||
|
||||
Grid_split(in, s_in);
|
||||
poly(SLinop, s_in, s_out);
|
||||
Grid_unsplit(in, s_out);
|
||||
|
||||
for (int u = 0; u < mrhs; u++)
|
||||
W[k_start + u] = in[u];
|
||||
|
||||
k_start += mrhs;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
|
||||
#endif // GRID_SPLIT_BLOCK_KRYLOV_SCHUR_H
|
||||
@@ -0,0 +1,366 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/iterative/TrueHarmonicBlockKrylovSchur.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Chulwoo Jung <chulwoo@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#ifndef GRID_TRUE_HARMONIC_BLOCKED_KRYLOV_SCHUR_H
|
||||
#define GRID_TRUE_HARMONIC_BLOCKED_KRYLOV_SCHUR_H
|
||||
|
||||
#include <Grid/algorithms/iterative/HarmonicBlockKrylovSchur.h>
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
/**
|
||||
* True harmonic-Ritz block Krylov-Schur eigensolver.
|
||||
*
|
||||
* Difference from the base class
|
||||
* ------------------------------
|
||||
* HarmonicBlockKrylovSchur is a *shift-targeted* Krylov-Schur: it Schur-
|
||||
* decomposes (H - sigma I) and sorts the standard Ritz values by |lambda -
|
||||
* sigma|. For interior eigenvalues of Hermitian indefinite operators the
|
||||
* standard Ritz values can be spurious ("ghosts"), so the sort can select
|
||||
* junk. This variant performs genuine harmonic Ritz extraction instead.
|
||||
*
|
||||
* Harmonic extraction
|
||||
* -------------------
|
||||
* From the exact block Arnoldi relation
|
||||
*
|
||||
* A V = V H + F B^dag (1)
|
||||
*
|
||||
* harmonic Ritz pairs (theta, g) w.r.t. shift sigma satisfy the Petrov-
|
||||
* Galerkin condition (A - sigma)Vg - (theta - sigma)Vg perp (A - sigma)V,
|
||||
* which reduces (with Hs = H - sigma I) to the small eigenproblem
|
||||
*
|
||||
* Hhat g = (theta - sigma) g, Hhat = Hs + Hs^{-H} B B^dag (2)
|
||||
*
|
||||
* Exact thick restart
|
||||
* -------------------
|
||||
* From (2), H g = theta g - Hs^{-H} B (B^dag g), so the residual of every
|
||||
* harmonic pair lies in the Nblock-dimensional column space of the single
|
||||
* block
|
||||
*
|
||||
* W = F - V Hs^{-H} B :
|
||||
* A (V g) - theta (V g) = W (B^dag g) (3)
|
||||
*
|
||||
* Hence {V g_1 .. g_Nk} + cols(W) admits an EXACT truncated Krylov-Schur
|
||||
* relation A Y = Y H_k + What Bc^dag with dense H_k, and block Arnoldi
|
||||
* resumes cleanly from What. Krylov-Schur (Stewart, SIMAX 23(3), 2001)
|
||||
* does not require H to be triangular after restart -- only that the
|
||||
* decomposition holds exactly, which (3) guarantees.
|
||||
*
|
||||
* This is the block analogue of the GMRES-DR restart (Morgan, SISC 24(1),
|
||||
* 2002; block version: Morgan, Appl. Numer. Math. 54, 2005). The exact
|
||||
* composition "block harmonic Krylov-Schur" is a derivation from these
|
||||
* ingredients rather than a published algorithm; the relation (1) is
|
||||
* checked explicitly at every restart when doVerify=true, and identity (3)
|
||||
* was validated to machine precision in a standalone Eigen prototype.
|
||||
*
|
||||
* Caveats
|
||||
* -------
|
||||
* - If sigma is (numerically) an eigenvalue of H, Hs^{-H} is singular;
|
||||
* an assert fires -- perturb the shift slightly.
|
||||
* - Reported eigenvalues come from the eigensystem of the retained H_k
|
||||
* (the true projected Rayleigh quotient Y^dag A Y), as in the base
|
||||
* class, so convergence tests and reporting are inherited unchanged.
|
||||
*
|
||||
* Usage: identical to HarmonicBlockKrylovSchur.
|
||||
*/
|
||||
template<class Field>
|
||||
class TrueHarmonicBlockKrylovSchur : public HarmonicBlockKrylovSchur<Field> {
|
||||
|
||||
typedef HarmonicBlockKrylovSchur<Field> Base;
|
||||
typedef typename Base::CMat CMat;
|
||||
typedef typename Base::CVec CVec;
|
||||
|
||||
// Members of the dependent base class need explicit scope.
|
||||
using Base::Nblock;
|
||||
using Base::Nm;
|
||||
using Base::Nk;
|
||||
using Base::Nstop;
|
||||
using Base::MaxIter;
|
||||
using Base::Tolerance;
|
||||
using Base::shift;
|
||||
using Base::Linop;
|
||||
using Base::Grid_;
|
||||
using Base::ritzFilter;
|
||||
using Base::basis;
|
||||
using Base::H;
|
||||
using Base::F;
|
||||
using Base::B;
|
||||
using Base::beta_k;
|
||||
using Base::rtol;
|
||||
using Base::evals;
|
||||
using Base::littleEvecs;
|
||||
using Base::ritzEstimates;
|
||||
|
||||
using Base::expandStartBlock;
|
||||
using Base::blockArnoldiIteration;
|
||||
using Base::blockQR;
|
||||
using Base::computeEigensystem;
|
||||
using Base::converged;
|
||||
using Base::approxMaxEval;
|
||||
|
||||
public:
|
||||
using Base::evecs;
|
||||
using Base::doEvalCheck;
|
||||
using Base::useParityFlip;
|
||||
using Base::useGamma5;
|
||||
using Base::gamma5Func;
|
||||
using Base::verify;
|
||||
|
||||
TrueHarmonicBlockKrylovSchur(LinearOperatorBase<Field>& _Linop, GridBase* _Grid,
|
||||
RealD _Tolerance, ComplexD _shift = 0.0,
|
||||
RitzFilter _rf = EvalNormSmall)
|
||||
: Base(_Linop, _Grid, _Tolerance, _shift, _rf)
|
||||
{}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Main entry point (same signature and outer structure as the base;
|
||||
// the Schur-sort restart is replaced by harmonicRestart()).
|
||||
//--------------------------------------------------------------------
|
||||
virtual void operator()(const std::vector<Field>& v0, int _maxIter, int _Nm, int _Nk,
|
||||
int _Nstop, int _Nblock = 1, bool doubleOrthog = true,
|
||||
bool doVerify = false) override
|
||||
{
|
||||
MaxIter = _maxIter;
|
||||
Nm = _Nm;
|
||||
Nk = _Nk;
|
||||
Nstop = _Nstop;
|
||||
Nblock = _Nblock;
|
||||
|
||||
{
|
||||
int divisor = 1;
|
||||
if (useParityFlip) divisor *= 2;
|
||||
if (useGamma5) divisor *= 2;
|
||||
assert(Nblock % divisor == 0 && (int)v0.size() >= Nblock / divisor);
|
||||
}
|
||||
assert(Nm % Nblock == 0);
|
||||
assert(Nk % Nblock == 0);
|
||||
assert(Nk < Nm);
|
||||
if (useGamma5) assert(gamma5Func && "useGamma5: gamma5Func must be set");
|
||||
|
||||
int N = Nm;
|
||||
|
||||
RealD approxLambdaMax = approxMaxEval(v0[0]);
|
||||
rtol = Tolerance * approxLambdaMax;
|
||||
std::cout << GridLogMessage
|
||||
<< "TrueHarmonicBlockKrylovSchur: approx max eval = " << approxLambdaMax
|
||||
<< ", rtol = " << rtol
|
||||
<< ", shift = " << shift << std::endl;
|
||||
|
||||
H = CMat::Zero(N, N);
|
||||
B = CMat::Zero(N, Nblock);
|
||||
|
||||
int start = 0;
|
||||
std::vector<Field> startBlock = expandStartBlock(v0);
|
||||
|
||||
for (int iter = 0; iter < MaxIter; iter++) {
|
||||
std::cout << GridLogMessage
|
||||
<< "TrueHarmonicBlockKrylovSchur: restart iteration " << iter << std::endl;
|
||||
|
||||
// ---- Block Arnoldi: extend from block 'start' to block Nm/Nblock ----
|
||||
blockArnoldiIteration(startBlock, Nm/Nblock, start, doubleOrthog);
|
||||
std::cout << GridLogMessage << "blockArnoldiIteration done " << std::endl;
|
||||
start = Nk/Nblock;
|
||||
|
||||
if (doVerify) {
|
||||
std::string lbl = "iter " + std::to_string(iter) + " after Arnoldi";
|
||||
verify(lbl);
|
||||
}
|
||||
|
||||
// ---- Harmonic extraction + exact thick restart ----
|
||||
harmonicRestart();
|
||||
std::cout << GridLogMessage << "harmonicRestart done " << std::endl;
|
||||
|
||||
// Restart from the residual block W (exact by identity (3))
|
||||
startBlock = F;
|
||||
|
||||
if (doVerify) {
|
||||
std::string lbl = "iter " + std::to_string(iter) + " after harmonic restart";
|
||||
verify(lbl);
|
||||
}
|
||||
|
||||
// ---- Eigensystem of retained H_k = Y^dag A Y for convergence ----
|
||||
CMat Hk = H(Eigen::seqN(0, Nk), Eigen::seqN(0, Nk));
|
||||
computeEigensystem(Hk, Nk);
|
||||
|
||||
int Nconv = converged(Nk);
|
||||
std::cout << GridLogMessage
|
||||
<< "TrueHarmonicBlockKrylovSchur: converged " << Nconv
|
||||
<< " / " << Nstop << std::endl;
|
||||
|
||||
if (Nconv >= Nstop || iter == MaxIter - 1) {
|
||||
std::cout << GridLogMessage
|
||||
<< "TrueHarmonicBlockKrylovSchur: done after " << iter
|
||||
<< " restarts, " << Nconv << " converged." << std::endl;
|
||||
std::cout << GridLogMessage << "Eigenvalues: " << evals.transpose() << std::endl;
|
||||
|
||||
if (doEvalCheck) {
|
||||
Field w(Grid_);
|
||||
for (int k = 0; k < (int)evecs.size(); k++) {
|
||||
Linop.Op(evecs[k], w);
|
||||
ComplexD eval_est = toStdCmplx(innerProduct(evecs[k], w));
|
||||
w -= eval_est * evecs[k];
|
||||
RealD res = std::sqrt(norm2(w));
|
||||
std::cout << GridLogMessage << "TrueHarmonicBlockKrylovSchur: evec[" << k << "]"
|
||||
<< " eval_reported = " << evals[k]
|
||||
<< " eval_est = " << eval_est
|
||||
<< " || A v - eval_est * v || = " << res << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Harmonic thick restart
|
||||
//--------------------------------------------------------------------
|
||||
// On entry: A V = V H + F B^dag exact, V = basis (Nm fields), F Nblock
|
||||
// residual fields, H/B the Nm-sized small matrices.
|
||||
// On exit: basis = Y (Nk orthonormal fields spanning the harmonic
|
||||
// Ritz space), F = What (Nblock orthonormal fields, perp Y),
|
||||
// H top-left Nk x Nk = Y^dag A Y (dense), B top Nk rows the
|
||||
// new coupling; relation A Y = Y H_k + F B^dag again exact.
|
||||
void harmonicRestart()
|
||||
{
|
||||
int N = Nm;
|
||||
|
||||
// ---- Small harmonic eigenproblem: Hhat g = (theta - sigma) g ----
|
||||
CMat Hs = H - shift * CMat::Identity(N, N);
|
||||
Eigen::FullPivLU<CMat> lu(Hs.adjoint());
|
||||
assert(lu.isInvertible() &&
|
||||
"TrueHarmonicBlockKrylovSchur: H - shift*I singular; perturb the shift");
|
||||
CMat M = lu.solve(B); // N x Nblock : Hs^{-H} B
|
||||
CMat Hhat = Hs + M * B.adjoint(); // N x N
|
||||
|
||||
Eigen::ComplexEigenSolver<CMat> es(Hhat);
|
||||
|
||||
// Sort harmonic values (theta - sigma) by the Ritz filter
|
||||
// (EvalNormSmall -> closest to the shift).
|
||||
ComplexComparator cComp(ritzFilter);
|
||||
std::vector<int> idx(N);
|
||||
std::iota(idx.begin(), idx.end(), 0);
|
||||
std::sort(idx.begin(), idx.end(), [&](int a, int b){
|
||||
return cComp(toStdCmplx(es.eigenvalues()(a)), toStdCmplx(es.eigenvalues()(b)));
|
||||
});
|
||||
|
||||
CMat G(N, Nk);
|
||||
CVec theta(Nk);
|
||||
for (int k = 0; k < Nk; k++) {
|
||||
G.col(k) = es.eigenvectors().col(idx[k]);
|
||||
theta(k) = es.eigenvalues()(idx[k]) + toStdCmplx(shift);
|
||||
}
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "TrueHarmonicBlockKrylovSchur: harmonic Ritz values nearest shift:" << std::endl;
|
||||
for (int k = 0; k < Nk; k++)
|
||||
std::cout << GridLogMessage << " [" << k << "] " << theta(k) << std::endl;
|
||||
|
||||
// ---- Orthonormalise the little vectors: G = Gt Rg ----
|
||||
Eigen::HouseholderQR<CMat> qr(G);
|
||||
CMat Gt = qr.householderQ() * CMat::Identity(N, Nk);
|
||||
CMat Rg = qr.matrixQR().topLeftCorner(Nk, Nk).template triangularView<Eigen::Upper>();
|
||||
for (int k = 0; k < Nk; k++)
|
||||
assert(std::abs(Rg(k, k)) > 1e-14 &&
|
||||
"TrueHarmonicBlockKrylovSchur: harmonic vectors linearly dependent");
|
||||
CMat RgInv = Rg.inverse();
|
||||
|
||||
// A (V G) = (V G) diag(theta) + W (B^dag G), W = F - V M
|
||||
// => A (V Gt) = (V Gt) T + W Ct
|
||||
CMat T = Rg * theta.asDiagonal() * RgInv; // Nk x Nk
|
||||
CMat Ct = (B.adjoint() * G) * RgInv; // Nblock x Nk
|
||||
|
||||
// ---- Large-field work ----
|
||||
// Y = V Gt : new orthonormal basis (Nk fields)
|
||||
std::vector<Field> Y;
|
||||
constructThin(Y, basis, Gt, Nk);
|
||||
|
||||
// W = F - V M : Nblock residual directions containing every harmonic
|
||||
// residual (identity (3) in the class comment)
|
||||
std::vector<Field> W = F;
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
for (int j = 0; j < N; j++)
|
||||
W[t] -= basis[j] * M(j, t);
|
||||
|
||||
// Orthogonalise W against Y (two passes), recording P = Y^dag W
|
||||
CMat P = CMat::Zero(Nk, Nblock);
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
for (int j = 0; j < Nk; j++) {
|
||||
for (int t = 0; t < Nblock; t++) {
|
||||
ComplexD c = innerProduct(Y[j], W[t]);
|
||||
P(j, t) += toStdCmplx(c);
|
||||
W[t] -= c * Y[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Block QR of the projected residual: W <- What, returns Rw
|
||||
CMat Rw = blockQR(W);
|
||||
|
||||
// ---- Reassemble the exact Krylov-Schur relation ----
|
||||
// A Y = Y (T + P Ct) + What (Rw Ct)
|
||||
CMat Hk = T + P * Ct; // Nk x Nk, dense
|
||||
CMat Bc = Rw * Ct; // Nblock x Nk
|
||||
|
||||
H = CMat::Zero(N, N);
|
||||
H(Eigen::seqN(0, Nk), Eigen::seqN(0, Nk)) = Hk;
|
||||
B = CMat::Zero(N, Nblock);
|
||||
for (int j = 0; j < Nk; j++)
|
||||
for (int t = 0; t < Nblock; t++)
|
||||
B(j, t) = std::conj(Bc(t, j));
|
||||
|
||||
basis = Y;
|
||||
F = W;
|
||||
beta_k = Bc.norm();
|
||||
|
||||
std::cout << GridLogMessage
|
||||
<< "TrueHarmonicBlockKrylovSchur: beta_k = " << beta_k << std::endl;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
// Thin basis combination: out[i] = sum_j U[j] * R(j,i), i < ncol
|
||||
//--------------------------------------------------------------------
|
||||
void constructThin(std::vector<Field>& out, const std::vector<Field>& U,
|
||||
const CMat& R, int ncol)
|
||||
{
|
||||
out.clear();
|
||||
Field tmp(Grid_);
|
||||
for (int i = 0; i < ncol; i++) {
|
||||
tmp = Zero();
|
||||
for (int j = 0; j < (int)U.size(); j++)
|
||||
tmp += U[j] * R(j, i);
|
||||
out.push_back(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
|
||||
#endif // GRID_TRUE_HARMONIC_BLOCKED_KRYLOV_SCHUR_H
|
||||
@@ -66,21 +66,7 @@ public:
|
||||
{
|
||||
};
|
||||
|
||||
void GlobalOrthonormalise(void)
|
||||
{
|
||||
// Normalise all vectors
|
||||
for(int i=0;i<nbasis; i++){
|
||||
RealD scale = std::pow(norm2(subspace[i]),-0.5);
|
||||
subspace[i] = subspace[i]*scale;
|
||||
}
|
||||
for(int i=0;i<nbasis; i++){
|
||||
for(int j=0;j<i; j++){
|
||||
basisOrthogonalize(subspace,subspace[i],j);
|
||||
}
|
||||
RealD scale = std::pow(norm2(subspace[i]),-0.5);
|
||||
subspace[i] = subspace[i]*scale;
|
||||
}
|
||||
}
|
||||
|
||||
void Orthogonalise(void){
|
||||
CoarseScalar InnerProd(CoarseGrid);
|
||||
// std::cout << GridLogMessage <<" Block Gramm-Schmidt pass 1"<<std::endl;
|
||||
@@ -124,16 +110,14 @@ public:
|
||||
|
||||
hermop.Op(noise,Mn); std::cout<<GridLogMessage << "noise ["<<b<<"] <n|MdagM|n> "<<norm2(Mn)<<std::endl;
|
||||
|
||||
for(int i=0;i<2;i++){
|
||||
for(int i=0;i<4;i++){
|
||||
|
||||
CG(hermop,noise,subspace[b]);
|
||||
|
||||
noise = subspace[b];
|
||||
scale = std::pow(norm2(noise),-0.5);
|
||||
noise=noise*scale;
|
||||
|
||||
hermop.Op(noise,Mn); std::cout<<GridLogMessage << "intermediate["<<i<<"] <i|MdagM|i> "<<norm2(Mn)<<std::endl;
|
||||
|
||||
|
||||
}
|
||||
|
||||
hermop.Op(noise,Mn); std::cout<<GridLogMessage << "filtered["<<b<<"] <f|MdagM|f> "<<norm2(Mn)<<std::endl;
|
||||
@@ -150,8 +134,7 @@ public:
|
||||
// PrecGeneralisedConjugateResidualNonHermitian<FineField> GCR(0.001,10,DiracOp,simple_fine,30,30);
|
||||
// PrecGeneralisedConjugateResidualNonHermitian<FineField> GCR(0.001,10,DiracOp,simple_fine,12,12);
|
||||
// PrecGeneralisedConjugateResidualNonHermitian<FineField> GCR(0.001,30,DiracOp,simple_fine,12,12);
|
||||
// PrecGeneralisedConjugateResidualNonHermitian<FineField> GCR(0.0005,30,DiracOp,simple_fine,20,20);
|
||||
PrecGeneralisedConjugateResidualNonHermitian<FineField> GCR(0.0005,30,DiracOp,simple_fine,10,10);
|
||||
PrecGeneralisedConjugateResidualNonHermitian<FineField> GCR(0.001,30,DiracOp,simple_fine,10,10);
|
||||
FineField noise(FineGrid);
|
||||
FineField src(FineGrid);
|
||||
FineField guess(FineGrid);
|
||||
@@ -184,8 +167,6 @@ public:
|
||||
noise = subspace[b];
|
||||
scale = std::pow(norm2(noise),-0.5);
|
||||
noise=noise*scale;
|
||||
|
||||
DiracOp.Op(noise,Mn); std::cout<<GridLogMessage << "intermediate["<<i<<"] <f|Op|f> "<<innerProduct(noise,Mn)<<" <f|OpDagOp|f>"<<norm2(Mn)<<std::endl;
|
||||
|
||||
}
|
||||
|
||||
@@ -193,7 +174,6 @@ public:
|
||||
subspace[b] = noise;
|
||||
|
||||
}
|
||||
GlobalOrthonormalise();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,7 +31,6 @@ Author: Peter Boyle <pboyle@bnl.gov>
|
||||
|
||||
#include <Grid/lattice/PaddedCell.h>
|
||||
#include <Grid/stencil/GeneralLocalStencil.h>
|
||||
#include <Grid/algorithms/deflation/MultiRHSBlockProject.h>
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
@@ -67,10 +66,6 @@ public:
|
||||
std::vector<CoarseMatrix> _Adag;
|
||||
std::vector<CoarseVector> MultTemporaries;
|
||||
|
||||
int64_t MultCalls;
|
||||
double MultFlopsAccum;
|
||||
double MultUsecAccum;
|
||||
|
||||
///////////////////////
|
||||
// Interface
|
||||
///////////////////////
|
||||
@@ -109,20 +104,19 @@ public:
|
||||
}
|
||||
*/
|
||||
|
||||
GeneralCoarsenedMatrix(NonLocalStencilGeometry &_geom,GridBase *FineGrid, GridCartesian * CoarseGrid,int _herm=1)
|
||||
GeneralCoarsenedMatrix(NonLocalStencilGeometry &_geom,GridBase *FineGrid, GridCartesian * CoarseGrid)
|
||||
: geom(_geom),
|
||||
_FineGrid(FineGrid),
|
||||
_CoarseGrid(CoarseGrid),
|
||||
hermitian(_herm),
|
||||
hermitian(1),
|
||||
Cell(_geom.Depth(),_CoarseGrid),
|
||||
Stencil(Cell.grids.back(),geom.shifts),
|
||||
MultCalls(0), MultFlopsAccum(0.0), MultUsecAccum(0.0)
|
||||
Stencil(Cell.grids.back(),geom.shifts)
|
||||
{
|
||||
{
|
||||
int npoint = _geom.npoint;
|
||||
}
|
||||
_A.resize(geom.npoint,CoarseGrid);
|
||||
if ( !hermitian ) _Adag.resize(geom.npoint,CoarseGrid);
|
||||
// _Adag.resize(geom.npoint,CoarseGrid);
|
||||
}
|
||||
void M (const CoarseVector &in, CoarseVector &out)
|
||||
{
|
||||
@@ -130,10 +124,10 @@ public:
|
||||
}
|
||||
void Mdag (const CoarseVector &in, CoarseVector &out)
|
||||
{
|
||||
if(hermitian)
|
||||
Mult(_A,in,out);
|
||||
else
|
||||
Mult(_Adag,in,out);
|
||||
GRID_ASSERT(hermitian);
|
||||
Mult(_A,in,out);
|
||||
// if ( hermitian ) M(in,out);
|
||||
// else Mult(_Adag,in,out);
|
||||
}
|
||||
void Mult (std::vector<CoarseMatrix> &A,const CoarseVector &in, CoarseVector &out)
|
||||
{
|
||||
@@ -233,28 +227,29 @@ public:
|
||||
text+=usecond();
|
||||
ttot+=usecond();
|
||||
|
||||
MultCalls++;
|
||||
MultFlopsAccum += flops;
|
||||
MultUsecAccum += ttot;
|
||||
std::cout << GridLogPerformance
|
||||
<< "Coarse Mult call " << MultCalls
|
||||
<< " tot " << ttot << " us"
|
||||
<< " kernel " << tmult << " us"
|
||||
<< " kernel " << flops/tmult*1e-3 << " GFlop/s"
|
||||
<< " overall " << MultFlopsAccum/MultUsecAccum*1e-3 << " GFlop/s (cumul)"
|
||||
<< " bw " << bytes/tmult*1e-3 << " GB/s"
|
||||
<< std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse 1rhs Mult Aviews "<<tviews<<" us"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Mult exch "<<texch<<" us"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Mult mult "<<tmult<<" us"<<std::endl;
|
||||
std::cout << GridLogPerformance<<" of which mult2 "<<tmult2<<" us"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Mult ext "<<text<<" us"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Mult temps "<<ttemps<<" us"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Mult copy "<<tcopy<<" us"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Mult tot "<<ttot<<" us"<<std::endl;
|
||||
// std::cout << GridLogPerformance<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Kernel flops "<< flops<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Kernel flop/s "<< flops/tmult<<" mflop/s"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse Kernel bytes/s "<< bytes/tmult<<" MB/s"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse overall flops/s "<< flops/ttot<<" mflop/s"<<std::endl;
|
||||
std::cout << GridLogPerformance<<"Coarse total bytes "<< bytes/1e6<<" MB"<<std::endl;
|
||||
|
||||
};
|
||||
|
||||
void PopulateAdag(void)
|
||||
{
|
||||
#if 0
|
||||
// Serial global peek/poke reference implementation
|
||||
for(int64_t bidx=0;bidx<CoarseGrid()->gSites() ;bidx++){
|
||||
Coordinate bcoor;
|
||||
CoarseGrid()->GlobalIndexToGlobalCoor(bidx,bcoor);
|
||||
|
||||
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
Coordinate scoor = bcoor;
|
||||
for(int mu=0;mu<bcoor.size();mu++){
|
||||
@@ -267,36 +262,6 @@ public:
|
||||
pokeSite(adj(link),_Adag[pp],bcoor);
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Parallel: _Adag[pp](x) = adj( _A[p](x + s_pp) ), pp = Reverse(p), s_pp = -s_p.
|
||||
// The neighbour fetch reuses the same padded-cell + stencil machinery as Mult,
|
||||
// reading one matrix element per coalesced access so no whole site matrix
|
||||
// (230KB at nbasis=60) ever lands on a GPU thread stack (HIP limit 128KB).
|
||||
// Halo sites compute garbage neighbours; Cell.Extract discards them.
|
||||
// Must run on the unpadded _A, i.e. before ExchangeCoarseLinks.
|
||||
const int Nsimd = CComplex::Nsimd();
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
int pp = geom.Reverse(p);
|
||||
CoarseMatrix Apad = Cell.ExchangePeriodic(_A[p]);
|
||||
CoarseMatrix Dpad(Apad.Grid());
|
||||
int64_t osites = Apad.Grid()->oSites();
|
||||
{
|
||||
autoView( Apad_v , Apad, AcceleratorRead);
|
||||
autoView( Dpad_v , Dpad, AcceleratorWriteDiscard);
|
||||
autoView( Stencil_v, Stencil, AcceleratorRead);
|
||||
accelerator_for(sj, osites*nbasis, Nsimd, {
|
||||
int32_t ss = sj/nbasis;
|
||||
int32_t j = sj%nbasis;
|
||||
auto SE = Stencil_v.GetEntry(pp,ss);
|
||||
for(int i=0;i<nbasis;i++){
|
||||
auto z = coalescedReadGeneralPermute(Apad_v[SE->_offset](i,j),SE->_permute,Nd);
|
||||
coalescedWrite(Dpad_v[ss](j,i),conjugate(z));
|
||||
}
|
||||
});
|
||||
}
|
||||
_Adag[pp] = Cell.Extract(Dpad);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
/////////////////////////////////////////////////////////////
|
||||
//
|
||||
@@ -452,19 +417,10 @@ public:
|
||||
int osites=CoarseGrid()->oSites();
|
||||
autoView( A_v , _A[k], AcceleratorWrite);
|
||||
autoView( FT_v , FT[k], AcceleratorRead);
|
||||
accelerator_for(sss, osites, nbasis, {
|
||||
#ifdef GRID_SIMT
|
||||
int j = acceleratorSIMTlane(nbasis);
|
||||
A_v[sss](i,j) = FT_v[sss](j);
|
||||
#else
|
||||
// CPU build: acceleratorSIMTlane()==0 -- an un-looped SIMT tensor
|
||||
// index writes ONLY j=0 and silently drops the other nbasis-1
|
||||
// columns (caught by Test_schur_dense_coarse import certificate,
|
||||
// 2026-08-14). Loop explicitly.
|
||||
accelerator_for(sss, osites, 1, {
|
||||
for(int j=0;j<nbasis;j++){
|
||||
A_v[sss](i,j) = FT_v[sss](j);
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
tinv+=usecond();
|
||||
@@ -472,8 +428,8 @@ public:
|
||||
|
||||
// Only needed if nonhermitian
|
||||
if ( ! hermitian ) {
|
||||
std::cout << GridLogMessage<<"PopulateAdag "<<std::endl;
|
||||
PopulateAdag();
|
||||
// std::cout << GridLogMessage<<"PopulateAdag "<<std::endl;
|
||||
// PopulateAdag();
|
||||
}
|
||||
|
||||
// Need to write something to populate Adag from A
|
||||
@@ -561,9 +517,13 @@ public:
|
||||
// Now compute the matrix elements of linop between the orthonormal
|
||||
// set of vectors.
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
FineField phaV(grid); // Phased block basis vector
|
||||
FineField MphaV(grid);// Matrix applied
|
||||
std::vector<FineComplexField> phaF(npoint,grid);
|
||||
std::vector<CoarseComplexField> pha(npoint,CoarseGrid());
|
||||
|
||||
|
||||
CoarseVector coarseInner(CoarseGrid());
|
||||
|
||||
typedef typename CComplex::scalar_type SComplex;
|
||||
FineComplexField one(grid); one=SComplex(1.0);
|
||||
FineComplexField zz(grid); zz = Zero();
|
||||
@@ -582,52 +542,37 @@ public:
|
||||
pha[p] =exp(pha[p]*ci);
|
||||
|
||||
blockZAXPY(phaF[p],pha[p],one,zz);
|
||||
|
||||
|
||||
}
|
||||
tphase+=usecond();
|
||||
|
||||
// Import basis into BLAS layout once; blockProject then reads it once per
|
||||
// basis vector rather than once per (i,p) as in scalar blockProject.
|
||||
// Process all npoint in a single batch.
|
||||
MultiRHSBlockProject<FineField> Projector;
|
||||
Projector.Allocate(nbasis, grid, CoarseGrid());
|
||||
Projector.ImportBasis(U.subspace);
|
||||
|
||||
std::vector<FineField> phaV_batch(npoint, grid);
|
||||
std::vector<FineField> MphaV_batch(npoint, grid);
|
||||
std::vector<CoarseVector> proj_batch(npoint, CoarseGrid());
|
||||
std::vector<CoarseVector> ComputeProj(npoint, CoarseGrid());
|
||||
std::vector<CoarseVector> FT(npoint, CoarseGrid());
|
||||
|
||||
// Pre-allocate BLAS_F and BLAS_C to avoid repeated hipMalloc/hipFree of
|
||||
// ~5.6 GB per blockProject call, which hangs on ROCm for large allocations.
|
||||
Projector.BLAS_F.resize(Projector.fine_vol * Projector.words * npoint);
|
||||
Projector.BLAS_C.resize(Projector.coarse_vol * nbasis * npoint);
|
||||
|
||||
|
||||
std::vector<CoarseVector> ComputeProj(npoint,CoarseGrid());
|
||||
std::vector<CoarseVector> FT(npoint,CoarseGrid());
|
||||
for(int i=0;i<nbasis;i++){// Loop over basis vectors
|
||||
accelerator_barrier(); // ensure prior iteration's async writes are retired
|
||||
std::cout << GridLogMessage<< "CoarsenMatrixColoured vec "<<i<<"/"<<nbasis<< std::endl;
|
||||
for(int p=0;p<npoint;p++){ // Loop over momenta in npoint
|
||||
tphaseBZ-=usecond();
|
||||
phaV = phaF[p]*V.subspace[i];
|
||||
tphaseBZ+=usecond();
|
||||
|
||||
tphaseBZ-=usecond();
|
||||
for(int p=0;p<npoint;p++)
|
||||
phaV_batch[p] = phaF[p] * V.subspace[i];
|
||||
tphaseBZ+=usecond();
|
||||
std::cout << GridLogMessage<< "CoarsenMatrixColoured vec "<<i<<" phaseBZ done"<< std::endl;
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// Multiple phased subspace vector by matrix and project to subspace
|
||||
// Remove local bulk phase to leave relative phases
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
tmat-=usecond();
|
||||
linop.Op(phaV,MphaV);
|
||||
tmat+=usecond();
|
||||
// std::cout << i << " " <<p << " MphaV "<<norm2(MphaV)<<" "<<norm2(phaV)<<std::endl;
|
||||
|
||||
tmat-=usecond();
|
||||
for(int p=0;p<npoint;p++)
|
||||
linop.Op(phaV_batch[p], MphaV_batch[p]);
|
||||
tmat+=usecond();
|
||||
std::cout << GridLogMessage<< "CoarsenMatrixColoured vec "<<i<<" mat done"<< std::endl;
|
||||
tproj-=usecond();
|
||||
blockProject(coarseInner,MphaV,U.subspace);
|
||||
coarseInner = conjugate(pha[p]) * coarseInner;
|
||||
|
||||
// One batched GEMM reads BLAS_V once for all npoint vectors.
|
||||
tproj-=usecond();
|
||||
Projector.blockProject(MphaV_batch, proj_batch);
|
||||
std::cout << GridLogMessage<< "CoarsenMatrixColoured vec "<<i<<" blockProject done"<< std::endl;
|
||||
for(int p=0;p<npoint;p++)
|
||||
ComputeProj[p] = conjugate(pha[p]) * proj_batch[p];
|
||||
tproj+=usecond();
|
||||
std::cout << GridLogMessage<< "CoarsenMatrixColoured vec "<<i<<" proj done"<< std::endl;
|
||||
ComputeProj[p] = coarseInner;
|
||||
tproj+=usecond();
|
||||
// std::cout << i << " " <<p << " ComputeProj "<<norm2(ComputeProj[p])<<std::endl;
|
||||
|
||||
}
|
||||
|
||||
tinv-=usecond();
|
||||
for(int k=0;k<npoint;k++){
|
||||
@@ -635,23 +580,14 @@ public:
|
||||
for(int l=0;l<npoint;l++){
|
||||
FT[k]= FT[k]+ invMkl(l,k)*ComputeProj[l];
|
||||
}
|
||||
|
||||
|
||||
int osites=CoarseGrid()->oSites();
|
||||
autoView( A_v , _A[k], AcceleratorWrite);
|
||||
autoView( FT_v , FT[k], AcceleratorRead);
|
||||
accelerator_for(sss, osites, nbasis, {
|
||||
#ifdef GRID_SIMT
|
||||
int j = acceleratorSIMTlane(nbasis);
|
||||
A_v[sss](i,j) = FT_v[sss](j);
|
||||
#else
|
||||
// CPU build: acceleratorSIMTlane()==0 -- an un-looped SIMT tensor
|
||||
// index writes ONLY j=0 and silently drops the other nbasis-1
|
||||
// columns (caught by Test_schur_dense_coarse import certificate,
|
||||
// 2026-08-14). Loop explicitly.
|
||||
accelerator_for(sss, osites, 1, {
|
||||
for(int j=0;j<nbasis;j++){
|
||||
A_v[sss](i,j) = FT_v[sss](j);
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
tinv+=usecond();
|
||||
@@ -659,13 +595,13 @@ public:
|
||||
|
||||
// Only needed if nonhermitian
|
||||
if ( ! hermitian ) {
|
||||
std::cout << GridLogMessage<<"PopulateAdag "<<std::endl;
|
||||
PopulateAdag();
|
||||
// std::cout << GridLogMessage<<"PopulateAdag "<<std::endl;
|
||||
// PopulateAdag();
|
||||
}
|
||||
|
||||
// for(int p=0;p<geom.npoint;p++){
|
||||
// std::cout << " _A["<<p<<"] "<<norm2(_A[p])<<std::endl;
|
||||
// }
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
std::cout << " _A["<<p<<"] "<<norm2(_A[p])<<std::endl;
|
||||
}
|
||||
|
||||
// Need to write something to populate Adag from A
|
||||
ExchangeCoarseLinks();
|
||||
@@ -680,7 +616,7 @@ public:
|
||||
void ExchangeCoarseLinks(void){
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
_A[p] = Cell.ExchangePeriodic(_A[p]);
|
||||
if ( !hermitian ) _Adag[p]= Cell.ExchangePeriodic(_Adag[p]);
|
||||
// _Adag[p]= Cell.ExchangePeriodic(_Adag[p]);
|
||||
}
|
||||
}
|
||||
virtual void Mdiag (const Field &in, Field &out){ GRID_ASSERT(0);};
|
||||
|
||||
@@ -1,851 +0,0 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/GeneralCoarsenedMatrixMultiRHS.h
|
||||
|
||||
Copyright (C) 2015
|
||||
|
||||
Author: Peter Boyle <pboyle@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#pragma once
|
||||
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
|
||||
// Fine Object == (per site) type of fine field
|
||||
// nbasis == number of deflation vectors
|
||||
template<class Fobj,class CComplex,int nbasis>
|
||||
class MultiGeneralCoarsenedOperatorV2 : public SparseMatrixBase<Lattice<iVector<CComplex,nbasis > > > {
|
||||
public:
|
||||
typedef typename CComplex::scalar_object SComplex;
|
||||
typedef GeneralCoarsenedMatrix<Fobj,CComplex,nbasis> GeneralCoarseOp;
|
||||
typedef MultiGeneralCoarsenedOperatorV2<Fobj,CComplex,nbasis> MultiGeneralCoarseOp;
|
||||
|
||||
typedef iVector<CComplex,nbasis > siteVector;
|
||||
typedef iMatrix<CComplex,nbasis > siteMatrix;
|
||||
typedef iVector<SComplex,nbasis > calcVector;
|
||||
typedef iMatrix<SComplex,nbasis > calcMatrix;
|
||||
typedef Lattice<iScalar<CComplex> > CoarseComplexField;
|
||||
typedef Lattice<siteVector> CoarseVector;
|
||||
typedef Lattice<iMatrix<CComplex,nbasis > > CoarseMatrix;
|
||||
typedef iMatrix<CComplex,nbasis > Cobj;
|
||||
typedef iVector<CComplex,nbasis > Cvec;
|
||||
typedef Lattice< CComplex > CoarseScalar; // used for inner products on fine field
|
||||
typedef Lattice<Fobj > FineField;
|
||||
typedef CoarseVector Field;
|
||||
|
||||
// Block operations on the fine vectors carry the fine layout, which need
|
||||
// not be the coarse one
|
||||
typedef decltype(innerProduct(Fobj(),Fobj())) FineInner;
|
||||
typedef Lattice<FineInner> FineComplexField;
|
||||
typedef Lattice<FineInner> BlockComplexField;
|
||||
|
||||
////////////////////
|
||||
// Data members
|
||||
//
|
||||
// Nrhs independent: the D dimensional coarse grid, the geometry, the padded
|
||||
// cell that supplies the stencil grid, the stencil, and the matrix elements.
|
||||
//
|
||||
// Nrhs dependent: the D+1 grid, its padded cell, and the BLAS B/C buffers
|
||||
// with their pointer tables. Owned by SetNRHS().
|
||||
////////////////////
|
||||
GridCartesian * _CoarseGrid; // D dimensional
|
||||
NonLocalStencilGeometry geom;
|
||||
NonLocalStencilGeometry geom_srhs;
|
||||
PaddedCell CellD; // D dimensional, supplies stencil grid
|
||||
GeneralLocalStencil Stencil; // D dimensional
|
||||
|
||||
int _Nrhs;
|
||||
GridCartesian * _CoarseGridMulti; // D+1 dimensional, SetNRHS
|
||||
PaddedCell * CellMulti; // D+1 dimensional, SetNRHS
|
||||
|
||||
deviceVector<calcVector> BLAS_B;
|
||||
deviceVector<calcVector> BLAS_C;
|
||||
std::vector<deviceVector<calcMatrix> > BLAS_A;
|
||||
|
||||
std::vector<deviceVector<ComplexD *> > BLAS_AP;
|
||||
std::vector<deviceVector<ComplexD *> > BLAS_BP;
|
||||
deviceVector<ComplexD *> BLAS_CP;
|
||||
|
||||
///////////////////////
|
||||
// Interface
|
||||
///////////////////////
|
||||
GridBase * Grid(void) { CheckGridSet(); return _CoarseGridMulti; };
|
||||
GridCartesian * CoarseGrid(void) { CheckGridSet(); return _CoarseGridMulti; };
|
||||
GridCartesian * CoarseGridD(void) { return _CoarseGrid; }; // lower dimensional grid
|
||||
int Nrhs(void) { CheckGridSet(); return _Nrhs; };
|
||||
|
||||
void CheckGridSet(void)
|
||||
{
|
||||
if ( _CoarseGridMulti == nullptr ) {
|
||||
std::cout << GridLogError
|
||||
<< "MultiGeneralCoarsenedOperatorV2: the multiRHS grid has not been set."
|
||||
<< std::endl;
|
||||
std::cout << GridLogError
|
||||
<< " Call SetGrid(CoarseGridMulti) with the D+1 dimensional grid your"
|
||||
<< std::endl;
|
||||
std::cout << GridLogError
|
||||
<< " coarse vectors live on, before Grid(), Nrhs() or M()."
|
||||
<< std::endl;
|
||||
GRID_ASSERT(_CoarseGridMulti != nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
// Can be used to do I/O on the operator matrices externally
|
||||
void SetMatrix (int p,CoarseMatrix & A)
|
||||
{
|
||||
GRID_ASSERT(A.size()==geom_srhs.npoint);
|
||||
GridtoBLAS(A[p],BLAS_A[p]);
|
||||
}
|
||||
void GetMatrix (int p,CoarseMatrix & A)
|
||||
{
|
||||
GRID_ASSERT(A.size()==geom_srhs.npoint);
|
||||
BLAStoGrid(A[p],BLAS_A[p]);
|
||||
}
|
||||
void CopyMatrix (GeneralCoarseOp &_Op)
|
||||
{
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
auto Aup = _Op.Cell.Extract(_Op._A[p]);
|
||||
//Unpadded
|
||||
GridtoBLAS(Aup,BLAS_A[p]);
|
||||
}
|
||||
}
|
||||
/*
|
||||
void CheckMatrix (GeneralCoarseOp &_Op)
|
||||
{
|
||||
std::cout <<"************* Checking the little direc operator mRHS"<<std::endl;
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
//Unpadded
|
||||
auto Aup = _Op.Cell.Extract(_Op._A[p]);
|
||||
auto Ack = Aup;
|
||||
BLAStoGrid(Ack,BLAS_A[p]);
|
||||
std::cout << p<<" Ack "<<norm2(Ack)<<std::endl;
|
||||
std::cout << p<<" Aup "<<norm2(Aup)<<std::endl;
|
||||
}
|
||||
std::cout <<"************* "<<std::endl;
|
||||
}
|
||||
*/
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Constructor takes the D dimensional coarse grid. Everything built here
|
||||
// is independent of Nrhs, in particular the matrix elements, which must
|
||||
// survive a change of Nrhs untouched.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
MultiGeneralCoarsenedOperatorV2(NonLocalStencilGeometry &_geom,GridCartesian *CoarseGrid) :
|
||||
_CoarseGrid(CoarseGrid),
|
||||
geom_srhs(_geom),
|
||||
geom(CoarseGrid,_geom.hops,_geom.skip),
|
||||
CellD(geom.Depth(),CoarseGrid),
|
||||
Stencil(CellD.grids.back(),geom.shifts), // D dimensional padded cell stencil
|
||||
_Nrhs(-1),
|
||||
_CoarseGridMulti(nullptr),
|
||||
CellMulti(nullptr)
|
||||
{
|
||||
int32_t unpadded_sites = _CoarseGrid->lSites();
|
||||
|
||||
/////////////////////////////////////////////////
|
||||
// Matrix elements and their pointer table
|
||||
/////////////////////////////////////////////////
|
||||
BLAS_A.resize(geom.npoint);
|
||||
BLAS_AP.resize(geom.npoint);
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
BLAS_A[p].resize (unpadded_sites); // no ghost zone, npoint elements
|
||||
BLAS_AP[p].resize(unpadded_sites);
|
||||
}
|
||||
|
||||
// Site identity mapping for A
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
for(int ss=0;ss<unpadded_sites;ss++){
|
||||
ComplexD *ptr = (ComplexD *)&BLAS_A[p][ss];
|
||||
acceleratorPut(BLAS_AP[p][ss],ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
virtual ~MultiGeneralCoarsenedOperatorV2()
|
||||
{
|
||||
ReleaseGrid();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Free everything SetGrid allocated. The D+1 grid is borrowed from the
|
||||
// caller and is never deleted here. Safe to call repeatedly and before
|
||||
// the destructor.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void ReleaseGrid(void)
|
||||
{
|
||||
if ( CellMulti != nullptr ) { delete CellMulti; CellMulti = nullptr; }
|
||||
|
||||
_CoarseGridMulti = nullptr; // borrowed, not owned
|
||||
_Nrhs = -1;
|
||||
|
||||
BLAS_B.resize(0);
|
||||
BLAS_C.resize(0);
|
||||
for(int p=0;p<BLAS_BP.size();p++){
|
||||
BLAS_BP[p].resize(0);
|
||||
}
|
||||
BLAS_BP.resize(0);
|
||||
BLAS_CP.resize(0);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Everything that depends on Nrhs. Idempotent; lazy called on demand.
|
||||
//
|
||||
// The stencil lives on the D dimensional padded grid. PaddedCell only pads
|
||||
// a dimension when it is distributed, and the rhs direction never is, so
|
||||
// the D+1 padded grid is exactly Nrhs copies of the D dimensional padded
|
||||
// grid with rhs innermost. The neighbour offset therefore carries an Nrhs
|
||||
// factor, in the same way the Nsimd factor is carried.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void SetGrid(GridCartesian *CoarseGridMulti)
|
||||
{
|
||||
GRID_ASSERT(CoarseGridMulti != nullptr);
|
||||
|
||||
if ( CoarseGridMulti == _CoarseGridMulti ) return; // idempotent on identity
|
||||
|
||||
ReleaseGrid();
|
||||
|
||||
/////////////////////////////////////////////////
|
||||
// The D+1 grid is supplied and owned by the caller. Two operators over
|
||||
// the same coarse space must share one grid object or their fields will
|
||||
// not conform, so this is never manufactured internally.
|
||||
/////////////////////////////////////////////////
|
||||
int nd = _CoarseGrid->_ndimension;
|
||||
|
||||
GRID_ASSERT(CoarseGridMulti->_ndimension == nd+1);
|
||||
GRID_ASSERT(CoarseGridMulti->_processors[0] == 1); // rhs is not distributed
|
||||
for(int d=0;d<nd;d++){
|
||||
GRID_ASSERT(CoarseGridMulti->_fdimensions[d+1] == _CoarseGrid->_fdimensions[d]);
|
||||
GRID_ASSERT(CoarseGridMulti->_processors [d+1] == _CoarseGrid->_processors [d]);
|
||||
GRID_ASSERT(CoarseGridMulti->_simd_layout[d+1] == _CoarseGrid->_simd_layout[d]);
|
||||
}
|
||||
|
||||
_CoarseGridMulti = CoarseGridMulti;
|
||||
_Nrhs = CoarseGridMulti->_fdimensions[0];
|
||||
GRID_ASSERT(_Nrhs>=1);
|
||||
|
||||
int nrhs = _Nrhs;
|
||||
|
||||
CellMulti = new PaddedCell(geom.Depth(),_CoarseGridMulti);
|
||||
|
||||
int32_t padded_sites = CellD.grids.back()->lSites(); // D dimensional
|
||||
int32_t unpadded_sites = _CoarseGrid->lSites(); // D dimensional
|
||||
|
||||
// The neighbour offset multiplication by nrhs is exact only if the D+1
|
||||
// padded volume is nrhs copies of the D dimensional one. Check it.
|
||||
GRID_ASSERT(CellMulti->grids.back()->lSites() == nrhs*padded_sites);
|
||||
GRID_ASSERT(_CoarseGridMulti->lSites() == nrhs*unpadded_sites);
|
||||
|
||||
/////////////////////////////////////////////////
|
||||
// Device data vector storage
|
||||
/////////////////////////////////////////////////
|
||||
BLAS_B.resize(nrhs *padded_sites); // includes ghost zone
|
||||
BLAS_C.resize(nrhs *unpadded_sites); // no ghost zone
|
||||
BLAS_BP.resize(geom.npoint);
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
BLAS_BP[p].resize(unpadded_sites);
|
||||
}
|
||||
BLAS_CP.resize(unpadded_sites);
|
||||
|
||||
// Site identity mapping for C
|
||||
for(int ss=0;ss<unpadded_sites;ss++){
|
||||
ComplexD *ptr = (ComplexD *)&BLAS_C[ss*nrhs];
|
||||
acceleratorPut(BLAS_CP[ss],ptr);
|
||||
}
|
||||
|
||||
// Neighbour table is more complicated
|
||||
int32_t j=0; // Interior point counter (unpadded)
|
||||
for(int32_t s=0;s<padded_sites;s++){ // D volume, padded
|
||||
int ghost_zone=0;
|
||||
for(int32_t point = 0 ; point < geom.npoint; point++){
|
||||
int i=s*geom.npoint+point;
|
||||
if( Stencil._entries[i]._wrap ) { // stencil is indexed by the oSite of the D dim grid
|
||||
ghost_zone=1; // If general stencil wrapped in any direction, wrap=1
|
||||
}
|
||||
}
|
||||
|
||||
if( ghost_zone==0) {
|
||||
for(int32_t point = 0 ; point < geom.npoint; point++){
|
||||
int i=s*geom.npoint+point;
|
||||
int32_t nbr = Stencil._entries[i]._offset*CComplex::Nsimd(); // oSite -> lSite, D dim
|
||||
nbr = nbr*nrhs; // D -> D+1, rhs innermost
|
||||
GRID_ASSERT(nbr<BLAS_B.size());
|
||||
ComplexD * ptr = (ComplexD *)&BLAS_B[nbr];
|
||||
acceleratorPut(BLAS_BP[point][j],ptr); // neighbour indexing in ghost zone volume
|
||||
}
|
||||
j++;
|
||||
}
|
||||
}
|
||||
GRID_ASSERT(j==unpadded_sites);
|
||||
}
|
||||
template<class vobj> void GridtoBLAS(const Lattice<vobj> &from,deviceVector<typename vobj::scalar_object> &to)
|
||||
{
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
typedef typename vobj::scalar_type scalar_type;
|
||||
typedef typename vobj::vector_type vector_type;
|
||||
|
||||
GridBase *Fg = from.Grid();
|
||||
GRID_ASSERT(!Fg->_isCheckerBoarded);
|
||||
int nd = Fg->_ndimension;
|
||||
|
||||
to.resize(Fg->lSites());
|
||||
|
||||
Coordinate LocalLatt = Fg->LocalDimensions();
|
||||
size_t nsite = 1;
|
||||
for(int i=0;i<nd;i++) nsite *= LocalLatt[i];
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// do the index calc on the GPU
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
Coordinate f_ostride = Fg->_ostride;
|
||||
Coordinate f_istride = Fg->_istride;
|
||||
Coordinate f_rdimensions = Fg->_rdimensions;
|
||||
|
||||
autoView(from_v,from,AcceleratorRead);
|
||||
auto to_v = &to[0];
|
||||
|
||||
const int words=sizeof(vobj)/sizeof(vector_type);
|
||||
accelerator_for(idx,nsite,1,{
|
||||
|
||||
Coordinate from_coor, base;
|
||||
Lexicographic::CoorFromIndex(base,idx,LocalLatt);
|
||||
for(int i=0;i<nd;i++){
|
||||
from_coor[i] = base[i];
|
||||
}
|
||||
int from_oidx = 0; for(int d=0;d<nd;d++) from_oidx+=f_ostride[d]*(from_coor[d]%f_rdimensions[d]);
|
||||
int from_lane = 0; for(int d=0;d<nd;d++) from_lane+=f_istride[d]*(from_coor[d]/f_rdimensions[d]);
|
||||
|
||||
const vector_type* from = (const vector_type *)&from_v[from_oidx];
|
||||
scalar_type* to = (scalar_type *)&to_v[idx];
|
||||
|
||||
scalar_type stmp;
|
||||
for(int w=0;w<words;w++){
|
||||
stmp = getlane(from[w], from_lane);
|
||||
to[w] = stmp;
|
||||
}
|
||||
});
|
||||
}
|
||||
template<class vobj> void BLAStoGrid(Lattice<vobj> &grid,deviceVector<typename vobj::scalar_object> &in)
|
||||
{
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
typedef typename vobj::scalar_type scalar_type;
|
||||
typedef typename vobj::vector_type vector_type;
|
||||
|
||||
GridBase *Tg = grid.Grid();
|
||||
GRID_ASSERT(!Tg->_isCheckerBoarded);
|
||||
int nd = Tg->_ndimension;
|
||||
|
||||
GRID_ASSERT(in.size()==Tg->lSites());
|
||||
|
||||
Coordinate LocalLatt = Tg->LocalDimensions();
|
||||
size_t nsite = 1;
|
||||
for(int i=0;i<nd;i++) nsite *= LocalLatt[i];
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// do the index calc on the GPU
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
Coordinate t_ostride = Tg->_ostride;
|
||||
Coordinate t_istride = Tg->_istride;
|
||||
Coordinate t_rdimensions = Tg->_rdimensions;
|
||||
|
||||
autoView(to_v,grid,AcceleratorWrite);
|
||||
auto from_v = &in[0];
|
||||
|
||||
const int words=sizeof(vobj)/sizeof(vector_type);
|
||||
accelerator_for(idx,nsite,1,{
|
||||
|
||||
Coordinate to_coor, base;
|
||||
Lexicographic::CoorFromIndex(base,idx,LocalLatt);
|
||||
for(int i=0;i<nd;i++){
|
||||
to_coor[i] = base[i];
|
||||
}
|
||||
int to_oidx = 0; for(int d=0;d<nd;d++) to_oidx+=t_ostride[d]*(to_coor[d]%t_rdimensions[d]);
|
||||
int to_lane = 0; for(int d=0;d<nd;d++) to_lane+=t_istride[d]*(to_coor[d]/t_rdimensions[d]);
|
||||
|
||||
vector_type* to = (vector_type *)&to_v[to_oidx];
|
||||
scalar_type* from = (scalar_type *)&from_v[idx];
|
||||
|
||||
scalar_type stmp;
|
||||
for(int w=0;w<words;w++){
|
||||
stmp=from[w];
|
||||
putlane(to[w], stmp, to_lane);
|
||||
}
|
||||
});
|
||||
}
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Shared by both CoarsenOperator variants
|
||||
//
|
||||
// conj(pha[block]) proj[k (which mom)][j (basis vec cpt)][block]
|
||||
// = \sum_{l in ball} e^{i q_k . delta_l} < phi_{block,j} | MdagM | phi_{(block+delta_l),i} >
|
||||
// = \sum_{l in ball} e^{iqk.delta_l} A_ji^{b.b+l}
|
||||
// = M_{kl} A_ji^{b.b+l}
|
||||
//
|
||||
// Where q_k = delta_k . (2*M_PI/global_nb[mu])
|
||||
// Then A{ji}^{b,b+l} = M^{-1}_{lm} ComputeProj_{m,b,i,j}
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void CoarsenFourierMatrix(GridBase *CoarseGrid,Eigen::MatrixXcd &invMkl)
|
||||
{
|
||||
const int npoint = geom_srhs.npoint;
|
||||
Coordinate clatt = CoarseGrid->GlobalDimensions();
|
||||
int Nd = CoarseGrid->Nd();
|
||||
|
||||
Eigen::MatrixXcd Mkl = Eigen::MatrixXcd::Zero(npoint,npoint);
|
||||
ComplexD ci(0.0,1.0);
|
||||
for(int k=0;k<npoint;k++){ // Loop over momenta
|
||||
for(int l=0;l<npoint;l++){ // Loop over nbr relative
|
||||
ComplexD phase(0.0,0.0);
|
||||
for(int mu=0;mu<Nd;mu++){
|
||||
RealD TwoPiL = M_PI * 2.0/ clatt[mu];
|
||||
phase=phase+TwoPiL*geom_srhs.shifts[k][mu]*geom_srhs.shifts[l][mu];
|
||||
}
|
||||
phase=exp(phase*ci);
|
||||
Mkl(k,l) = phase;
|
||||
}
|
||||
}
|
||||
invMkl = Mkl.inverse();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// blockOrthogonalise and blockZAXPY are block operations on the fine
|
||||
// vectors, using a coarse shaped field only as an index set. They need a
|
||||
// grid carrying the fine SIMD layout, which the coarse space no longer
|
||||
// does. Constructed local to the caller so it cannot be mistaken for the
|
||||
// coarse grid.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void CoarsenBlockGridLayout(GridBase *grid,GridBase *CoarseGrid,
|
||||
Coordinate &latt,Coordinate &simd,Coordinate &mpi)
|
||||
{
|
||||
int nd = CoarseGrid->_ndimension;
|
||||
latt.resize(nd); simd.resize(nd); mpi.resize(nd);
|
||||
for(int d=0;d<nd;d++){
|
||||
latt[d] = CoarseGrid->_fdimensions[d];
|
||||
simd[d] = grid->_simd_layout[d];
|
||||
mpi [d] = CoarseGrid->_processors[d];
|
||||
}
|
||||
}
|
||||
|
||||
// D+1 coarse grid holding the batch, rhs innermost and unvectorised
|
||||
void CoarsenBatchGridLayout(GridBase *CoarseGrid,int batch,
|
||||
Coordinate &latt,Coordinate &simd,Coordinate &mpi)
|
||||
{
|
||||
latt.resize(1,batch); simd.resize(1,1); mpi.resize(1,1);
|
||||
latt[0]=batch; simd[0]=1; mpi[0]=1;
|
||||
for(int d=0;d<CoarseGrid->_ndimension;d++){
|
||||
latt.push_back(CoarseGrid->_fdimensions[d]);
|
||||
simd.push_back(CoarseGrid->_simd_layout[d]);
|
||||
mpi .push_back(CoarseGrid->_processors[d]);
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// The Fourier inverse needs the phase in the coarse layout and the basis
|
||||
// phasing needs it in the fine layout; each is built from its own
|
||||
// coordinates rather than transferred.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void CoarsenPhases(GridBase *grid,GridBase *CoarseGrid,GridCartesian *BlockGrid,
|
||||
std::vector<CoarseComplexField> &pha,
|
||||
std::vector<FineComplexField> &phaF)
|
||||
{
|
||||
const int npoint = geom_srhs.npoint;
|
||||
Coordinate clatt = CoarseGrid->GlobalDimensions();
|
||||
int Nd = CoarseGrid->Nd();
|
||||
ComplexD ci(0.0,1.0);
|
||||
|
||||
typedef typename CComplex::scalar_type SComplex;
|
||||
FineComplexField one(grid); one=SComplex(1.0);
|
||||
FineComplexField zz(grid); zz = Zero();
|
||||
BlockComplexField pha_blk (BlockGrid);
|
||||
BlockComplexField blk_coor(BlockGrid);
|
||||
|
||||
for(int p=0;p<npoint;p++){ // Loop over momenta in npoint
|
||||
CoarseComplexField coor(CoarseGrid);
|
||||
pha[p] =Zero();
|
||||
pha_blk=Zero();
|
||||
for(int mu=0;mu<Nd;mu++){
|
||||
RealD TwoPiL = M_PI * 2.0/ clatt[mu];
|
||||
LatticeCoordinate(coor,mu);
|
||||
pha[p] = pha[p] + (TwoPiL * geom_srhs.shifts[p][mu]) * coor;
|
||||
LatticeCoordinate(blk_coor,mu);
|
||||
pha_blk = pha_blk + (TwoPiL * geom_srhs.shifts[p][mu]) * blk_coor;
|
||||
}
|
||||
pha[p] =exp(pha[p] *ci);
|
||||
pha_blk=exp(pha_blk*ci);
|
||||
|
||||
blockZAXPY(phaF[p],pha_blk,one,zz);
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Remove the bulk phase from the batch of coarse projections and
|
||||
// accumulate the Fourier inverse into A. Both variants reach here with
|
||||
// TmpProj in the same batch coarse order, so this is shared verbatim.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void CoarsenAccumulate(int p,int i0,int nbv,int batch,
|
||||
Eigen::MatrixXcd &invMkl,
|
||||
std::vector<CoarseComplexField> &pha,
|
||||
CoarseComplexField &phaB,
|
||||
CoarseVector &TmpProj,
|
||||
std::vector<CoarseMatrix> &_A,
|
||||
GridBase *CoarseGrid)
|
||||
{
|
||||
typedef typename CComplex::scalar_type SComplex;
|
||||
const int npoint = geom_srhs.npoint;
|
||||
|
||||
for(int b=0;b<batch;b++) InsertSliceFast(pha[p],phaB,b,0);
|
||||
TmpProj = conjugate(phaB)*TmpProj;
|
||||
|
||||
int osites=CoarseGrid->oSites();
|
||||
for(int k=0;k<npoint;k++){
|
||||
SComplex sc(invMkl(p,k).real(),invMkl(p,k).imag());
|
||||
CComplex coef(sc);
|
||||
autoView( A_v , _A[k], AcceleratorWrite);
|
||||
autoView( TP_v , TmpProj, AcceleratorRead);
|
||||
accelerator_for(sss, osites, 1, {
|
||||
for(int b=0;b<nbv;b++){
|
||||
for(int j=0;j<nbasis;j++){
|
||||
A_v[sss](i0+b,j) = A_v[sss](i0+b,j) + coef*TP_v[b+batch*sss](j);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void CoarsenReport(RealD tphase,RealD tphaseBZ,RealD tslice,
|
||||
RealD tmat,RealD tproj,RealD tinv)
|
||||
{
|
||||
std::cout << GridLogMessage<<"CoarsenOperator phase "<<tphase<<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"CoarsenOperator phaseBZ "<<tphaseBZ<<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"CoarsenOperator slice "<<tslice <<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"CoarsenOperator mat "<<tmat <<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"CoarsenOperator proj "<<tproj<<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"CoarsenOperator inv "<<tinv<<" us"<<std::endl;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Coarsen a NATIVELY multiRHS fine operator.
|
||||
//
|
||||
// linop acts on the D+1 dimensional fine grid FineGridMulti, with the batch
|
||||
// of phased basis vectors carried in the rhs direction. A single RHS
|
||||
// operator can be promoted with MrhsPromotedOperator, but that pays an
|
||||
// ExtractSlice/InsertSlice pair per rhs; prefer the single RHS variant
|
||||
// below in that case.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void CoarsenOperator(LinearOperatorBase<Lattice<Fobj> > &linop,
|
||||
GridCartesian *FineGridMulti,
|
||||
std::vector<FineField> &Subspace,
|
||||
GridBase *CoarseGrid)
|
||||
{
|
||||
RealD tproj=0.0, tmat=0.0, tphase=0.0, tphaseBZ=0.0, tslice=0.0, tinv=0.0;
|
||||
|
||||
std::cout << GridLogMessage<< "GeneralCoarsenMatrixMrhs (multiRHS fine operator)"<< std::endl;
|
||||
|
||||
GRID_ASSERT(Subspace.size()==nbasis);
|
||||
GridBase *grid = Subspace[0].Grid();
|
||||
|
||||
GRID_ASSERT(FineGridMulti->_ndimension == grid->_ndimension+1);
|
||||
GRID_ASSERT(FineGridMulti->_processors[0] == 1);
|
||||
for(int d=0;d<grid->_ndimension;d++){
|
||||
GRID_ASSERT(FineGridMulti->_fdimensions[d+1] == grid->_fdimensions[d]);
|
||||
GRID_ASSERT(FineGridMulti->_processors [d+1] == grid->_processors [d]);
|
||||
}
|
||||
int batch = FineGridMulti->_fdimensions[0];
|
||||
|
||||
Coordinate blatt,bsimd,bmpi;
|
||||
CoarsenBlockGridLayout(grid,CoarseGrid,blatt,bsimd,bmpi);
|
||||
GridCartesian BlockGrid(blatt,bsimd,bmpi);
|
||||
|
||||
BlockComplexField InnerProd(&BlockGrid);
|
||||
blockOrthogonalise(InnerProd,Subspace);
|
||||
|
||||
MultiRHSBlockProject<Lattice<Fobj> > Projector;
|
||||
Projector.Allocate(nbasis,grid,CoarseGrid);
|
||||
Projector.ImportBasis(Subspace);
|
||||
|
||||
const int npoint = geom_srhs.npoint;
|
||||
|
||||
Eigen::MatrixXcd invMkl;
|
||||
CoarsenFourierMatrix(CoarseGrid,invMkl);
|
||||
|
||||
FineField phaV(grid);
|
||||
std::vector<FineComplexField> phaF(npoint,grid);
|
||||
std::vector<CoarseComplexField> pha (npoint,CoarseGrid);
|
||||
|
||||
tphase=-usecond();
|
||||
CoarsenPhases(grid,CoarseGrid,&BlockGrid,pha,phaF);
|
||||
tphase+=usecond();
|
||||
|
||||
std::vector<CoarseMatrix> _A;
|
||||
_A.resize(npoint,CoarseGrid);
|
||||
for(int k=0;k<npoint;k++) _A[k] = Zero();
|
||||
|
||||
Coordinate cmlatt,cmsimd,cmmpi;
|
||||
CoarsenBatchGridLayout(CoarseGrid,batch,cmlatt,cmsimd,cmmpi);
|
||||
GridCartesian CoarseBatchGrid(cmlatt,cmsimd,cmmpi);
|
||||
|
||||
CoarseVector TmpProj(&CoarseBatchGrid);
|
||||
CoarseComplexField phaB(&CoarseBatchGrid);
|
||||
|
||||
FineField hi_in (FineGridMulti);
|
||||
FineField hi_out(FineGridMulti);
|
||||
FineField zzF(grid); zzF = Zero();
|
||||
|
||||
for(int i0=0;i0<nbasis;i0+=batch){ // Loop over batches of basis vectors
|
||||
|
||||
int nbv = MIN(batch,nbasis-i0);
|
||||
std::cout << GridLogMessage<< "CoarsenMatrixColoured vec "<<i0<<"/"<<nbasis<< std::endl;
|
||||
|
||||
for(int p=0;p<npoint;p++){ // Loop over momenta
|
||||
|
||||
// One phase, applied to the whole batch. Tail slices are zeroed so
|
||||
// the operator never sees undefined data.
|
||||
for(int b=0;b<nbv;b++){
|
||||
tphaseBZ-=usecond();
|
||||
phaV = phaF[p]*Subspace[i0+b];
|
||||
tphaseBZ+=usecond();
|
||||
tslice-=usecond();
|
||||
InsertSliceFast(phaV,hi_in,b,0);
|
||||
tslice+=usecond();
|
||||
}
|
||||
tslice-=usecond();
|
||||
for(int b=nbv;b<batch;b++){
|
||||
InsertSliceFast(zzF,hi_in,b,0);
|
||||
}
|
||||
tslice+=usecond();
|
||||
|
||||
tmat-=usecond();
|
||||
linop.Op(hi_in,hi_out);
|
||||
tmat+=usecond();
|
||||
|
||||
tproj-=usecond();
|
||||
Projector.blockProject(hi_out,TmpProj);
|
||||
tproj+=usecond();
|
||||
|
||||
tinv-=usecond();
|
||||
CoarsenAccumulate(p,i0,nbv,batch,invMkl,pha,phaB,TmpProj,_A,CoarseGrid);
|
||||
tinv+=usecond();
|
||||
}
|
||||
}
|
||||
|
||||
for(int p=0;p<npoint;p++){
|
||||
GridtoBLAS(_A[p],BLAS_A[p]);
|
||||
}
|
||||
CoarsenReport(tphase,tphaseBZ,tslice,tmat,tproj,tinv);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Coarsen a SINGLE RHS fine operator.
|
||||
//
|
||||
// No multiRHS packing: the operator is applied once per phased basis
|
||||
// vector and the batch is assembled on the coarse side by the mixed
|
||||
// blockProject, which takes a vector of fine fields and writes the batch
|
||||
// coarse field the accumulate expects. Only nbv applications per momentum,
|
||||
// so a batch that does not divide nbasis wastes nothing, and the live fine
|
||||
// storage is batch fields rather than two D+1 fields of extent batch.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void CoarsenOperator(LinearOperatorBase<Lattice<Fobj> > &linop,
|
||||
std::vector<FineField> &Subspace,
|
||||
GridBase *CoarseGrid,
|
||||
int batch)
|
||||
{
|
||||
RealD tproj=0.0, tmat=0.0, tphase=0.0, tphaseBZ=0.0, tslice=0.0, tinv=0.0;
|
||||
|
||||
std::cout << GridLogMessage<< "GeneralCoarsenMatrixMrhs (single RHS fine operator)"<< std::endl;
|
||||
|
||||
GRID_ASSERT(Subspace.size()==nbasis);
|
||||
GRID_ASSERT(batch>=1);
|
||||
GridBase *grid = Subspace[0].Grid();
|
||||
|
||||
Coordinate blatt,bsimd,bmpi;
|
||||
CoarsenBlockGridLayout(grid,CoarseGrid,blatt,bsimd,bmpi);
|
||||
GridCartesian BlockGrid(blatt,bsimd,bmpi);
|
||||
|
||||
BlockComplexField InnerProd(&BlockGrid);
|
||||
blockOrthogonalise(InnerProd,Subspace);
|
||||
|
||||
MultiRHSBlockProject<Lattice<Fobj> > Projector;
|
||||
Projector.Allocate(nbasis,grid,CoarseGrid);
|
||||
Projector.ImportBasis(Subspace);
|
||||
|
||||
const int npoint = geom_srhs.npoint;
|
||||
|
||||
Eigen::MatrixXcd invMkl;
|
||||
CoarsenFourierMatrix(CoarseGrid,invMkl);
|
||||
|
||||
FineField phaV(grid);
|
||||
std::vector<FineComplexField> phaF(npoint,grid);
|
||||
std::vector<CoarseComplexField> pha (npoint,CoarseGrid);
|
||||
|
||||
tphase=-usecond();
|
||||
CoarsenPhases(grid,CoarseGrid,&BlockGrid,pha,phaF);
|
||||
tphase+=usecond();
|
||||
|
||||
std::vector<CoarseMatrix> _A;
|
||||
_A.resize(npoint,CoarseGrid);
|
||||
for(int k=0;k<npoint;k++) _A[k] = Zero();
|
||||
|
||||
Coordinate cmlatt,cmsimd,cmmpi;
|
||||
CoarsenBatchGridLayout(CoarseGrid,batch,cmlatt,cmsimd,cmmpi);
|
||||
GridCartesian CoarseBatchGrid(cmlatt,cmsimd,cmmpi);
|
||||
|
||||
CoarseVector TmpProj(&CoarseBatchGrid);
|
||||
CoarseComplexField phaB(&CoarseBatchGrid);
|
||||
|
||||
std::vector<FineField> MphaV(batch,grid);
|
||||
|
||||
for(int i0=0;i0<nbasis;i0+=batch){ // Loop over batches of basis vectors
|
||||
|
||||
int nbv = MIN(batch,nbasis-i0);
|
||||
std::cout << GridLogMessage<< "CoarsenMatrixColoured vec "<<i0<<"/"<<nbasis<< std::endl;
|
||||
|
||||
for(int p=0;p<npoint;p++){ // Loop over momenta
|
||||
|
||||
for(int b=0;b<nbv;b++){
|
||||
tphaseBZ-=usecond();
|
||||
phaV = phaF[p]*Subspace[i0+b];
|
||||
tphaseBZ+=usecond();
|
||||
tmat-=usecond();
|
||||
linop.Op(phaV,MphaV[b]);
|
||||
tmat+=usecond();
|
||||
}
|
||||
// The accumulate reads only the first nbv slices, but the projector
|
||||
// sees the whole vector, so the tail must not be undefined.
|
||||
for(int b=nbv;b<batch;b++) MphaV[b] = Zero();
|
||||
|
||||
tproj-=usecond();
|
||||
Projector.blockProject(MphaV,TmpProj);
|
||||
tproj+=usecond();
|
||||
|
||||
tinv-=usecond();
|
||||
CoarsenAccumulate(p,i0,nbv,batch,invMkl,pha,phaB,TmpProj,_A,CoarseGrid);
|
||||
tinv+=usecond();
|
||||
}
|
||||
}
|
||||
|
||||
for(int p=0;p<npoint;p++){
|
||||
GridtoBLAS(_A[p],BLAS_A[p]);
|
||||
}
|
||||
CoarsenReport(tphase,tphaseBZ,tslice,tmat,tproj,tinv);
|
||||
}
|
||||
void Mdag(const CoarseVector &in, CoarseVector &out)
|
||||
{
|
||||
this->M(in,out);
|
||||
}
|
||||
void M (const CoarseVector &in, CoarseVector &out)
|
||||
{
|
||||
// std::cout << GridLogMessage << "New Mrhs coarse"<<std::endl;
|
||||
conformable(CoarseGrid(),in.Grid());
|
||||
conformable(in.Grid(),out.Grid());
|
||||
out.Checkerboard() = in.Checkerboard();
|
||||
|
||||
RealD t_tot;
|
||||
RealD t_exch;
|
||||
RealD t_GtoB;
|
||||
RealD t_BtoG;
|
||||
RealD t_mult;
|
||||
|
||||
CheckGridSet();
|
||||
if ( in.Grid() != _CoarseGridMulti ) {
|
||||
std::cout << GridLogError
|
||||
<< "MultiGeneralCoarsenedOperatorV2::M called with a field on a"
|
||||
<< std::endl;
|
||||
std::cout << GridLogError
|
||||
<< " different grid object from the one given to SetGrid(). Two"
|
||||
<< std::endl;
|
||||
std::cout << GridLogError
|
||||
<< " grids of identical shape do not conform; share one object."
|
||||
<< std::endl;
|
||||
GRID_ASSERT(in.Grid() == _CoarseGridMulti);
|
||||
}
|
||||
|
||||
t_tot=-usecond();
|
||||
CoarseVector tin=in;
|
||||
t_exch=-usecond();
|
||||
CoarseVector pin = CellMulti->ExchangePeriodic(tin); //padded input
|
||||
t_exch+=usecond();
|
||||
|
||||
CoarseVector pout(pin.Grid());
|
||||
|
||||
int npoint = geom.npoint;
|
||||
typedef calcMatrix* Aview;
|
||||
typedef LatticeView<Cvec> Vview;
|
||||
|
||||
const int Nsimd = CComplex::Nsimd();
|
||||
|
||||
int64_t nrhs =pin.Grid()->GlobalDimensions()[0];
|
||||
GRID_ASSERT(nrhs>=1);
|
||||
|
||||
RealD flops,bytes;
|
||||
int64_t osites=in.Grid()->oSites(); // unpadded
|
||||
int64_t unpadded_vol = CoarseGrid()->lSites()/nrhs;
|
||||
|
||||
flops = 1.0* npoint * nbasis * nbasis * 8.0 * osites * CComplex::Nsimd();
|
||||
bytes = 1.0*osites*sizeof(siteMatrix)*npoint/pin.Grid()->GlobalDimensions()[0]
|
||||
+ 2.0*osites*sizeof(siteVector)*npoint;
|
||||
|
||||
|
||||
t_GtoB=-usecond();
|
||||
GridtoBLAS(pin,BLAS_B);
|
||||
t_GtoB+=usecond();
|
||||
|
||||
GridBLAS BLAS;
|
||||
|
||||
t_mult=-usecond();
|
||||
for(int p=0;p<geom.npoint;p++){
|
||||
RealD c = 1.0;
|
||||
if (p==0) c = 0.0;
|
||||
ComplexD beta(c);
|
||||
|
||||
BLAS.gemmBatched(nbasis,nrhs,nbasis,
|
||||
ComplexD(1.0),
|
||||
BLAS_AP[p],
|
||||
BLAS_BP[p],
|
||||
ComplexD(c),
|
||||
BLAS_CP);
|
||||
}
|
||||
BLAS.synchronise();
|
||||
t_mult+=usecond();
|
||||
|
||||
t_BtoG=-usecond();
|
||||
BLAStoGrid(out,BLAS_C);
|
||||
t_BtoG+=usecond();
|
||||
t_tot+=usecond();
|
||||
/*
|
||||
std::cout << GridLogMessage << "New Mrhs coarse DONE "<<std::endl;
|
||||
std::cout << GridLogMessage<<"Coarse Mult exch "<<t_exch<<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"Coarse Mult mult "<<t_mult<<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"Coarse Mult GtoB "<<t_GtoB<<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"Coarse Mult BtoG "<<t_BtoG<<" us"<<std::endl;
|
||||
std::cout << GridLogMessage<<"Coarse Mult tot "<<t_tot<<" us"<<std::endl;
|
||||
*/
|
||||
// std::cout << GridLogMessage<<std::endl;
|
||||
// std::cout << GridLogMessage<<"Coarse Kernel flops "<< flops<<std::endl;
|
||||
// std::cout << GridLogMessage<<"Coarse Kernel flop/s "<< flops/t_mult<<" mflop/s"<<std::endl;
|
||||
// std::cout << GridLogMessage<<"Coarse Kernel bytes/s "<< bytes/t_mult/1000<<" GB/s"<<std::endl;
|
||||
// std::cout << GridLogMessage<<"Coarse overall flops/s "<< flops/t_tot<<" mflop/s"<<std::endl;
|
||||
// std::cout << GridLogMessage<<"Coarse total bytes "<< bytes/1e6<<" MB"<<std::endl;
|
||||
};
|
||||
virtual void Mdiag (const Field &in, Field &out){ GRID_ASSERT(0);};
|
||||
virtual void Mdir (const Field &in, Field &out,int dir, int disp){assert(0);};
|
||||
virtual void MdirAll (const Field &in, std::vector<Field> &out){assert(0);};
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -1,161 +0,0 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/algorithms/multigrid/MrhsPromotedOperator.h
|
||||
|
||||
Copyright (C) 2026
|
||||
|
||||
Author: Peter Boyle <pboyle@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#pragma once
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Present a D dimensional operator as a D+1 dimensional operator with Nrhs in
|
||||
// dimension 0. Field type is unchanged; only the Grid differs, so this is a
|
||||
// LinearOperatorBase and callers need no template parameter: a native mrhs
|
||||
// operator derives from the same base and substitutes without a call site
|
||||
// change.
|
||||
//
|
||||
// Slices in and out around the wrapped operator. No arithmetic beyond the
|
||||
// wrapped call, but one ExtractSliceFast/InsertSliceFast pair per right hand
|
||||
// side: data motion, not work.
|
||||
//
|
||||
// AdjOp is carried so that A^dag may be coarsened as a separate coarse
|
||||
// operator when needed, rather than doubling coarse storage.
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
template<class Field>
|
||||
class MrhsPromotedOperator : public LinearOperatorBase<Field>
|
||||
{
|
||||
private:
|
||||
|
||||
LinearOperatorBase<Field> &_LinOp;
|
||||
GridBase *_LowGrid;
|
||||
int _Nrhs;
|
||||
|
||||
public:
|
||||
|
||||
MrhsPromotedOperator(LinearOperatorBase<Field> &LinOp,GridBase *LowGrid,int Nrhs)
|
||||
: _LinOp(LinOp), _LowGrid(LowGrid), _Nrhs(Nrhs)
|
||||
{
|
||||
GRID_ASSERT(_Nrhs>=1);
|
||||
}
|
||||
|
||||
GridBase *LowGrid(void) { return _LowGrid; }
|
||||
int Nrhs(void) { return _Nrhs; }
|
||||
|
||||
// Reset on each call; retrieve and accumulate in the caller
|
||||
RealD tslice;
|
||||
RealD top;
|
||||
|
||||
void OpDiag (const Field &in, Field &out)
|
||||
{
|
||||
SliceLoop(in,out,[&](Field &i,Field &o){ _LinOp.OpDiag(i,o); });
|
||||
}
|
||||
|
||||
void Op (const Field &in, Field &out)
|
||||
{
|
||||
SliceLoop(in,out,[&](Field &i,Field &o){ _LinOp.Op(i,o); });
|
||||
}
|
||||
|
||||
void AdjOp (const Field &in, Field &out)
|
||||
{
|
||||
SliceLoop(in,out,[&](Field &i,Field &o){ _LinOp.AdjOp(i,o); });
|
||||
}
|
||||
|
||||
void HermOp (const Field &in, Field &out)
|
||||
{
|
||||
SliceLoop(in,out,[&](Field &i,Field &o){ _LinOp.HermOp(i,o); });
|
||||
}
|
||||
|
||||
void OpDir (const Field &in, Field &out,int dir,int disp)
|
||||
{
|
||||
SliceLoop(in,out,[&](Field &i,Field &o){ _LinOp.OpDir(i,o,dir,disp); });
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////
|
||||
// Norms of the D+1 field are the sums over slices
|
||||
//////////////////////////////////////////////////////////////////
|
||||
void HermOpAndNorm(const Field &in, Field &out,RealD &n1,RealD &n2)
|
||||
{
|
||||
Conformable(in,out);
|
||||
Field lo_in (_LowGrid);
|
||||
Field lo_out(_LowGrid);
|
||||
n1=0.0;
|
||||
n2=0.0;
|
||||
for(int r=0;r<_Nrhs;r++){
|
||||
RealD r1,r2;
|
||||
ExtractSliceFast(lo_in,in,r,0);
|
||||
_LinOp.HermOpAndNorm(lo_in,lo_out,r1,r2);
|
||||
InsertSliceFast(lo_out,out,r,0);
|
||||
n1=n1+r1;
|
||||
n2=n2+r2;
|
||||
}
|
||||
}
|
||||
|
||||
void OpDirAll(const Field &in, std::vector<Field> &out)
|
||||
{
|
||||
int npoint = out.size();
|
||||
Field lo_in(_LowGrid);
|
||||
std::vector<Field> lo_out(npoint,_LowGrid);
|
||||
for(int r=0;r<_Nrhs;r++){
|
||||
ExtractSliceFast(lo_in,in,r,0);
|
||||
_LinOp.OpDirAll(lo_in,lo_out);
|
||||
for(int p=0;p<npoint;p++){
|
||||
InsertSliceFast(lo_out[p],out[p],r,0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void Conformable(const Field &in,const Field &out)
|
||||
{
|
||||
conformable(in.Grid(),out.Grid());
|
||||
GRID_ASSERT(in.Grid()->_ndimension == _LowGrid->_ndimension+1);
|
||||
GRID_ASSERT(in.Grid()->_fdimensions[0] == _Nrhs);
|
||||
}
|
||||
|
||||
template<class Kernel>
|
||||
void SliceLoop(const Field &in,Field &out,Kernel K)
|
||||
{
|
||||
Conformable(in,out);
|
||||
Field lo_in (_LowGrid);
|
||||
Field lo_out(_LowGrid);
|
||||
tslice=0.0;
|
||||
top=0.0;
|
||||
for(int r=0;r<_Nrhs;r++){
|
||||
tslice-=usecond();
|
||||
ExtractSliceFast(lo_in,in,r,0);
|
||||
tslice+=usecond();
|
||||
top-=usecond();
|
||||
K(lo_in,lo_out);
|
||||
top+=usecond();
|
||||
tslice-=usecond();
|
||||
InsertSliceFast(lo_out,out,r,0);
|
||||
tslice+=usecond();
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -32,5 +32,3 @@ Author: Peter Boyle <pboyle@bnl.gov>
|
||||
#include <Grid/algorithms/multigrid/CoarsenedMatrix.h>
|
||||
#include <Grid/algorithms/multigrid/GeneralCoarsenedMatrix.h>
|
||||
#include <Grid/algorithms/multigrid/GeneralCoarsenedMatrixMultiRHS.h>
|
||||
#include <Grid/algorithms/multigrid/GeneralCoarsenedMatrixMultiRHSV2.h>
|
||||
#include <Grid/algorithms/multigrid/MrhsPromotedOperator.h>
|
||||
@@ -1,617 +0,0 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: RecursiveSchurInverse.h
|
||||
|
||||
Copyright (C) 2026
|
||||
|
||||
Author: Peter Boyle <pboyle@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#pragma once
|
||||
|
||||
#include <Grid/algorithms/blas/BatchedBlas.h>
|
||||
#include <Grid/algorithms/blas/BatchedInverse.h>
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// RecursiveSchurInverse: distributed dense inversion by recursive Schur
|
||||
// complement over a binary rank-range tree.
|
||||
//
|
||||
// Contract: rank r owns global rows [rowStart[r], rowStart[r+1]) of an
|
||||
// N x N matrix in rank-major ordering, and receives its rows of the
|
||||
// inverse in the same layout. Consumes GridBase collectives, GridBLAS
|
||||
// and GridBLASInverse only; Eigen reference backends permit CPU unit
|
||||
// testing under mpirun (Test_schur_inverse).
|
||||
//
|
||||
// Arithmetic is fp64 throughout; the caller rounds once into fp32 storage.
|
||||
//
|
||||
// Execution: SPMD full-tree walk. Every rank makes the identical call
|
||||
// sequence; data participation is ownership-gated; all collectives are
|
||||
// world-wide, so no deadlock surface exists.
|
||||
//
|
||||
// Storage: BlockRows is column-major, ld = rows; element (i,j) at
|
||||
// data[i + j*ld]; a column window is the contiguous slice at data[col0*ld].
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// My rows of a distributed dense matrix: rows x cols, column major, ld = rows.
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
class BlockRows
|
||||
{
|
||||
public:
|
||||
deviceVector<ComplexD> data;
|
||||
int64_t rows;
|
||||
int64_t cols;
|
||||
int64_t ld;
|
||||
|
||||
BlockRows()
|
||||
{
|
||||
rows = 0;
|
||||
cols = 0;
|
||||
ld = 0;
|
||||
}
|
||||
void Resize(int64_t r, int64_t c)
|
||||
{
|
||||
rows = r;
|
||||
cols = c;
|
||||
ld = r;
|
||||
data.resize((uint64_t)r*c);
|
||||
}
|
||||
ComplexD *ColumnWindow(int64_t col0)
|
||||
{
|
||||
GRID_ASSERT( col0 >= 0 );
|
||||
GRID_ASSERT( col0 <= cols );
|
||||
return &data[(uint64_t)col0*ld];
|
||||
}
|
||||
};
|
||||
|
||||
class RecursiveSchurInverse
|
||||
{
|
||||
public:
|
||||
GridBase *grid; // world collectives only
|
||||
int64_t N; // global matrix dimension
|
||||
int P; // ranks
|
||||
int me; // this rank
|
||||
std::vector<int64_t> rowStart; // P+1 entries: rank-major row ownership
|
||||
int64_t myRow0;
|
||||
int64_t myNrows;
|
||||
int64_t panelBytes; // gather panel budget (DENSE_PANEL_BYTES)
|
||||
|
||||
GridBLAS BLAS;
|
||||
GridBLASInverse INV;
|
||||
|
||||
// Growth telemetry: one entry per merge node, walk order
|
||||
std::vector<double> telNormB; // ||B||_F = ||A11inv A12||_F
|
||||
std::vector<double> telSratio; // ||S||_F / ||A22||_F
|
||||
double telLeafMaxInv; // max |(leaf inverse)_ij| over leaves
|
||||
|
||||
// Phase timers/counters, reported by ReportTelemetry
|
||||
double tMemset; // device panel zero-fill
|
||||
double tDeposit; // owner rows -> panel (device kernel)
|
||||
double tAllreduce; // GlobalSumVector on device panels
|
||||
double tGemm; // strided gemm + synchronise
|
||||
double tLeaf; // leaf inversions
|
||||
double tARmin; // fastest single panel collective
|
||||
double tARmax; // slowest single panel collective
|
||||
uint64_t bytesAllreduce;
|
||||
uint64_t nAllreduce; // panel collectives
|
||||
uint64_t nGatherGemm; // GatherGemm calls
|
||||
|
||||
// Persistent grow-only device panel; assembly and collectives are
|
||||
// device-resident. Device builds require GPU-aware MPI.
|
||||
deviceVector<ComplexD> dPanelBuf;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Ownership-table validation: a proper partition of [0,N).
|
||||
// Static and communicator-free so synthetic tables unit-test directly.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
static void CheckRowStart(const std::vector<int64_t> &table, int64_t N)
|
||||
{
|
||||
int P = (int)table.size() - 1;
|
||||
GRID_ASSERT( P >= 1 );
|
||||
GRID_ASSERT( table[0] == 0 );
|
||||
GRID_ASSERT( table[P] == N );
|
||||
for(int r=0; r<P; r++)
|
||||
{
|
||||
GRID_ASSERT( table[r+1] >= table[r] ); // zero-row ranks permitted
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Build the ownership table from each rank's local row count: zero-fill
|
||||
// allgather (the standing comms idiom) then prefix sum. Every rank
|
||||
// returns the identical table.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
static std::vector<int64_t> MakeRowStart(GridBase *g, int64_t myNrows)
|
||||
{
|
||||
int P = g->ProcessorCount();
|
||||
int me = g->ThisRank();
|
||||
|
||||
std::vector<uint64_t> counts(P, 0);
|
||||
counts[me] = (uint64_t)myNrows;
|
||||
g->GlobalSumVector(&counts[0], P);
|
||||
|
||||
std::vector<int64_t> table(P+1);
|
||||
table[0] = 0;
|
||||
for(int r=0; r<P; r++)
|
||||
{
|
||||
table[r+1] = table[r] + (int64_t)counts[r];
|
||||
}
|
||||
CheckRowStart(table, table[P]);
|
||||
return table;
|
||||
}
|
||||
|
||||
RecursiveSchurInverse(GridBase *g,
|
||||
int64_t N_,
|
||||
std::vector<int64_t> &rowStart_,
|
||||
int64_t panelBytes_)
|
||||
{
|
||||
grid = g;
|
||||
N = N_;
|
||||
P = g->ProcessorCount();
|
||||
me = g->ThisRank();
|
||||
rowStart = rowStart_;
|
||||
panelBytes = panelBytes_;
|
||||
|
||||
GRID_ASSERT( (int)rowStart.size() == P+1 );
|
||||
CheckRowStart(rowStart, N);
|
||||
|
||||
myRow0 = rowStart[me];
|
||||
myNrows = rowStart[me+1] - rowStart[me];
|
||||
|
||||
telLeafMaxInv = 0.0;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// The communication primitive.
|
||||
//
|
||||
// C(:, colC : colC+widthB) <- beta * C(:, colC : colC+widthB)
|
||||
// + alpha * A(:, colA : colA+widthA) * Bsub
|
||||
//
|
||||
// Bsub is the widthA x widthB sub-block of a row-distributed operand
|
||||
// owned by ranks [rB0, rB1): owner r contributes its rows of
|
||||
// B(:, colB : colB+widthB) at sub-block row offset
|
||||
// rowStart[r] - rowStart[rB0], gathered in panelBytes row-chunks by
|
||||
// device zero-fill + deposit kernel + GlobalSumVector.
|
||||
//
|
||||
// Every rank calls; non-owners of B add zeros; ranks with A.rows == 0
|
||||
// skip local compute but make every collective call. Column offsets
|
||||
// are local buffer offsets -- non-participants pass 0.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void GatherGemm(ComplexD alpha,
|
||||
BlockRows &A, int64_t colA, int64_t widthA,
|
||||
int rB0, int rB1,
|
||||
BlockRows &B, int64_t colB, int64_t widthB,
|
||||
ComplexD beta,
|
||||
BlockRows &C, int64_t colC)
|
||||
{
|
||||
GRID_ASSERT( rB0 >= 0 );
|
||||
GRID_ASSERT( rB1 > rB0 );
|
||||
GRID_ASSERT( rB1 <= P );
|
||||
|
||||
int64_t k = rowStart[rB1] - rowStart[rB0];
|
||||
int64_t m = A.rows;
|
||||
int64_t n = widthB;
|
||||
GRID_ASSERT( widthA == k );
|
||||
GRID_ASSERT( n >= 1 );
|
||||
|
||||
int owner = ( me >= rB0 ) && ( me < rB1 ) && ( B.rows > 0 );
|
||||
int64_t myOff = 0;
|
||||
if ( owner )
|
||||
{
|
||||
myOff = rowStart[me] - rowStart[rB0];
|
||||
}
|
||||
|
||||
if ( m > 0 )
|
||||
{
|
||||
GRID_ASSERT( colA + widthA <= A.cols );
|
||||
GRID_ASSERT( colC + widthB <= C.cols );
|
||||
GRID_ASSERT( C.rows == m );
|
||||
}
|
||||
|
||||
nGatherGemm++;
|
||||
GRID_TRACE("GatherGemm");
|
||||
|
||||
if ( owner )
|
||||
{
|
||||
GRID_ASSERT( colB + widthB <= B.cols );
|
||||
}
|
||||
|
||||
int64_t kc = panelBytes / ( (int64_t)sizeof(ComplexD) * n );
|
||||
if ( kc < 1 ) kc = 1;
|
||||
if ( kc > k ) kc = k;
|
||||
GRID_ASSERT( kc*n < 2147483647L ); // GlobalSumVector count is int
|
||||
|
||||
deviceVector<ComplexD> &dPanel = dPanelBuf;
|
||||
if ( dPanel.size() < (uint64_t)kc*n ) dPanel.resize((uint64_t)kc*n);
|
||||
deviceVector<ComplexD*> ap(1);
|
||||
deviceVector<ComplexD*> bp(1);
|
||||
deviceVector<ComplexD*> cp(1);
|
||||
std::vector<ComplexD*> ptr(1);
|
||||
|
||||
for(int64_t k0=0; k0<k; k0+=kc)
|
||||
{
|
||||
int64_t kchunk = std::min(kc, k-k0);
|
||||
|
||||
// Zeroing must complete before MPI reads the panel; it is the sole
|
||||
// producer on non-owner ranks.
|
||||
tMemset -= usecond();
|
||||
acceleratorMemSet(&dPanel[0], 0, (uint64_t)kchunk*n*sizeof(ComplexD));
|
||||
tMemset += usecond();
|
||||
if ( owner )
|
||||
{
|
||||
int64_t i0 = std::max(k0, myOff);
|
||||
int64_t i1 = std::min(k0+kchunk, myOff+B.rows);
|
||||
if ( i1 > i0 )
|
||||
{
|
||||
// Deposit my rows: strided block copy, len rows x n columns
|
||||
int64_t len = i1-i0;
|
||||
int64_t brows = B.rows;
|
||||
int64_t dof = i0-k0;
|
||||
int64_t sof = i0-myOff;
|
||||
ComplexD *src = B.ColumnWindow(colB);
|
||||
ComplexD *dst = &dPanel[0];
|
||||
tDeposit -= usecond();
|
||||
accelerator_for(idx, (uint64_t)(len*n), 1, {
|
||||
int64_t j = idx / len;
|
||||
int64_t i = idx % len;
|
||||
dst[(uint64_t)(dof + i + j*kchunk)] = src[(uint64_t)(sof + i + j*brows)];
|
||||
});
|
||||
tDeposit += usecond();
|
||||
}
|
||||
}
|
||||
double tar = -usecond();
|
||||
grid->GlobalSumVector(&dPanel[0], (int)(kchunk*n));
|
||||
tar += usecond();
|
||||
tAllreduce += tar;
|
||||
tARmin = std::min(tARmin, tar);
|
||||
tARmax = std::max(tARmax, tar);
|
||||
bytesAllreduce += (uint64_t)kchunk*n*sizeof(ComplexD);
|
||||
nAllreduce++;
|
||||
|
||||
if ( m > 0 )
|
||||
{
|
||||
ComplexD beta_use = ( k0==0 ) ? beta : ComplexD(1.0,0.0);
|
||||
|
||||
ptr[0] = A.ColumnWindow(colA + k0);
|
||||
acceleratorCopyToDevice(&ptr[0], &ap[0], sizeof(ComplexD*));
|
||||
ptr[0] = &dPanel[0];
|
||||
acceleratorCopyToDevice(&ptr[0], &bp[0], sizeof(ComplexD*));
|
||||
ptr[0] = C.ColumnWindow(colC);
|
||||
acceleratorCopyToDevice(&ptr[0], &cp[0], sizeof(ComplexD*));
|
||||
|
||||
tGemm -= usecond();
|
||||
BLAS.gemmBatched(GridBLAS_OP_N, GridBLAS_OP_N,
|
||||
(int)m, (int)n, (int)kchunk,
|
||||
alpha, ap, (int)A.ld,
|
||||
bp, (int)kchunk,
|
||||
beta_use, cp, (int)C.ld);
|
||||
BLAS.synchronise();
|
||||
tGemm += usecond();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Local Frobenius norm-squared of a full-height column window.
|
||||
// NO comms; callers GlobalSum the result. Host staging, setup-scale.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
double FrobNorm2Local(BlockRows &X, int64_t col0, int64_t w)
|
||||
{
|
||||
if ( X.rows == 0 ) return 0.0;
|
||||
GRID_ASSERT( col0 + w <= X.cols );
|
||||
uint64_t len = (uint64_t)X.rows*w;
|
||||
std::vector<ComplexD> h(len);
|
||||
acceleratorCopyFromDevice(X.ColumnWindow(col0), &h[0], len*sizeof(ComplexD));
|
||||
// Member real()/imag(): portable across std::complex (CPU) and
|
||||
// thrust::complex (HIP), where std::norm does not resolve.
|
||||
double s = 0.0;
|
||||
for(uint64_t i=0; i<len; i++)
|
||||
{
|
||||
double re = h[i].real();
|
||||
double im = h[i].imag();
|
||||
s += re*re + im*im;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// dst(:, dcol0 : dcol0+w) = - src(:, 0:w). Both operands have ld == rows
|
||||
// so full-height windows are contiguous: flat elementwise device copy.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void NegateCopy(BlockRows &src, BlockRows &dst, int64_t dcol0, int64_t w)
|
||||
{
|
||||
GRID_ASSERT( src.rows == dst.rows );
|
||||
GRID_ASSERT( w <= src.cols );
|
||||
GRID_ASSERT( dcol0 + w <= dst.cols );
|
||||
if ( src.rows == 0 ) return;
|
||||
uint64_t len = (uint64_t)src.rows*w;
|
||||
ComplexD *s = &src.data[0];
|
||||
ComplexD *d = dst.ColumnWindow(dcol0);
|
||||
accelerator_for(i, len, 1, {
|
||||
d[i] = -s[i];
|
||||
});
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Leaf inversion: local, in place on the contiguous diagonal window.
|
||||
// No collectives.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void LeafInvert(int64_t col0, int64_t width, BlockRows &Arows)
|
||||
{
|
||||
GRID_TRACE("SchurLeaf");
|
||||
GRID_ASSERT( width == Arows.rows );
|
||||
GRID_ASSERT( col0 + width <= Arows.cols );
|
||||
int64_t w = width;
|
||||
uint64_t len = (uint64_t)w*w;
|
||||
tLeaf -= usecond();
|
||||
|
||||
deviceVector<ComplexD*> bp(1);
|
||||
std::vector<ComplexD*> ptr(1);
|
||||
ptr[0] = Arows.ColumnWindow(col0);
|
||||
acceleratorCopyToDevice(&ptr[0], &bp[0], sizeof(ComplexD*));
|
||||
INV.inverseBatched(w, bp);
|
||||
|
||||
// Telemetry: max |element| of the leaf inverse
|
||||
{
|
||||
std::vector<ComplexD> h(len);
|
||||
acceleratorCopyFromDevice(Arows.ColumnWindow(col0), &h[0], len*sizeof(ComplexD));
|
||||
double mx = 0.0;
|
||||
for(uint64_t i=0; i<len; i++)
|
||||
{
|
||||
double re = h[i].real();
|
||||
double im = h[i].imag();
|
||||
mx = std::max(mx, re*re + im*im);
|
||||
}
|
||||
telLeafMaxInv = std::max(telLeafMaxInv, std::sqrt(mx));
|
||||
}
|
||||
tLeaf += usecond();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// The recursion (plan 3.5 / 4B.3). Inverts the diagonal block of the
|
||||
// rank-major matrix spanned by ranks [r0, r1), living in every member
|
||||
// rank's column window [col0, col0+width) -- IN PLACE.
|
||||
//
|
||||
// SPMD: every rank calls with IDENTICAL (r0, r1, width) and its own
|
||||
// local (col0, Arows); ranks outside [r0, r1) participate in the
|
||||
// collectives only (dummy operands, zero contributions). The collective
|
||||
// sequence -- 5 GatherGemm calls + 3 scalar GlobalSums per merge node --
|
||||
// is identical on every rank by construction.
|
||||
//
|
||||
// I = [r0, mid) J = [mid, r1) widths WI, WJ
|
||||
// 1. recurse I: A11 -> A11inv
|
||||
// 2. B = A11inv.A12 (I rows)
|
||||
// 3. C = A21.A11inv (J rows)
|
||||
// 4. S = A22 - A21.B in place (J rows) [alpha=-1, beta=1]
|
||||
// 5. recurse J: S -> Sinv
|
||||
// 6. T = Sinv.C (J rows)
|
||||
// 7. U = B.Sinv (I rows)
|
||||
// 8. X11 = A11inv + U.C in place (I rows) [beta=1]
|
||||
// 9. X12 = -U, X21 = -T local negates; X22 = Sinv already in place
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void SchurNode(int r0, int r1, int64_t col0, int64_t width, BlockRows &Arows)
|
||||
{
|
||||
int span = r1 - r0;
|
||||
GRID_ASSERT( span >= 1 );
|
||||
GRID_ASSERT( width == rowStart[r1] - rowStart[r0] );
|
||||
|
||||
if ( span == 1 )
|
||||
{
|
||||
if ( ( me == r0 ) && ( myNrows > 0 ) )
|
||||
{
|
||||
LeafInvert(col0, width, Arows);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
int mid = ( r0 + r1 ) / 2;
|
||||
int64_t WI = rowStart[mid] - rowStart[r0];
|
||||
int64_t WJ = rowStart[r1] - rowStart[mid];
|
||||
|
||||
// Zero-width child ranges (all ranks of a half owning no rows) are a
|
||||
// KNOWN LIMITATION: fail loudly rather than divide mysteriously.
|
||||
GRID_ASSERT( WI > 0 );
|
||||
GRID_ASSERT( WJ > 0 );
|
||||
|
||||
int inI = ( me >= r0 ) && ( me < mid );
|
||||
int inJ = ( me >= mid ) && ( me < r1 );
|
||||
|
||||
ComplexD one ( 1.0,0.0);
|
||||
ComplexD mone (-1.0,0.0);
|
||||
ComplexD zero ( 0.0,0.0);
|
||||
|
||||
BlockRows dummy;
|
||||
|
||||
// 1. A11 -> A11inv
|
||||
SchurNode(r0, mid, col0, WI, Arows);
|
||||
|
||||
// 2. B = A11inv . A12 (I rows; gather A12 from I owners)
|
||||
BlockRows Bbuf;
|
||||
if ( inI ) Bbuf.Resize(myNrows, WJ);
|
||||
{
|
||||
BlockRows &Aop = inI ? Arows : dummy;
|
||||
BlockRows &Cop = inI ? Bbuf : dummy;
|
||||
int64_t cA = inI ? col0 : 0;
|
||||
GatherGemm(one, Aop, cA, WI,
|
||||
r0, mid,
|
||||
Arows, col0+WI, WJ,
|
||||
zero, Cop, 0);
|
||||
}
|
||||
double nB = FrobNorm2Local(Bbuf, 0, inI ? WJ : 0);
|
||||
grid->GlobalSumVector(&nB, 1);
|
||||
telNormB.push_back(std::sqrt(nB));
|
||||
|
||||
// 3. C = A21 . A11inv (J rows; gather A11inv from I owners)
|
||||
BlockRows Cbuf;
|
||||
if ( inJ ) Cbuf.Resize(myNrows, WI);
|
||||
{
|
||||
BlockRows &Aop = inJ ? Arows : dummy;
|
||||
BlockRows &Cop = inJ ? Cbuf : dummy;
|
||||
int64_t cA = inJ ? col0 : 0;
|
||||
GatherGemm(one, Aop, cA, WI,
|
||||
r0, mid,
|
||||
Arows, col0, WI,
|
||||
zero, Cop, 0);
|
||||
}
|
||||
|
||||
// 4. S = A22 - A21 . B in place on my A22 window (J rows)
|
||||
double nA22 = FrobNorm2Local( inJ ? Arows : dummy, inJ ? col0+WI : 0, inJ ? WJ : 0 );
|
||||
grid->GlobalSumVector(&nA22, 1);
|
||||
{
|
||||
BlockRows &Aop = inJ ? Arows : dummy;
|
||||
BlockRows &Cop = inJ ? Arows : dummy;
|
||||
int64_t cA = inJ ? col0 : 0;
|
||||
int64_t cC = inJ ? col0+WI : 0;
|
||||
GatherGemm(mone, Aop, cA, WI,
|
||||
r0, mid,
|
||||
Bbuf, 0, WJ,
|
||||
one, Cop, cC);
|
||||
}
|
||||
double nS = FrobNorm2Local( inJ ? Arows : dummy, inJ ? col0+WI : 0, inJ ? WJ : 0 );
|
||||
grid->GlobalSumVector(&nS, 1);
|
||||
telSratio.push_back( std::sqrt(nS) / ( std::sqrt(nA22) + 1.0e-300 ) );
|
||||
|
||||
// 5. S -> Sinv
|
||||
SchurNode(mid, r1, col0+WI, WJ, Arows);
|
||||
|
||||
// 6. T = Sinv . C (J rows; gather C from J owners)
|
||||
BlockRows Tbuf;
|
||||
if ( inJ ) Tbuf.Resize(myNrows, WI);
|
||||
{
|
||||
BlockRows &Aop = inJ ? Arows : dummy;
|
||||
BlockRows &Cop = inJ ? Tbuf : dummy;
|
||||
int64_t cA = inJ ? col0+WI : 0;
|
||||
GatherGemm(one, Aop, cA, WJ,
|
||||
mid, r1,
|
||||
Cbuf, 0, WI,
|
||||
zero, Cop, 0);
|
||||
}
|
||||
|
||||
// 7. U = B . Sinv (I rows; gather Sinv from J owners)
|
||||
BlockRows Ubuf;
|
||||
if ( inI ) Ubuf.Resize(myNrows, WJ);
|
||||
{
|
||||
BlockRows &Aop = inI ? Bbuf : dummy;
|
||||
BlockRows &Cop = inI ? Ubuf : dummy;
|
||||
GatherGemm(one, Aop, 0, WJ,
|
||||
mid, r1,
|
||||
Arows, col0+WI, WJ,
|
||||
zero, Cop, 0);
|
||||
}
|
||||
|
||||
// 8. X11 = A11inv + U . C in place (I rows; gather C from J owners)
|
||||
{
|
||||
BlockRows &Aop = inI ? Ubuf : dummy;
|
||||
BlockRows &Cop = inI ? Arows : dummy;
|
||||
int64_t cC = inI ? col0 : 0;
|
||||
GatherGemm(one, Aop, 0, WJ,
|
||||
mid, r1,
|
||||
Cbuf, 0, WI,
|
||||
one, Cop, cC);
|
||||
}
|
||||
|
||||
// 9. Off-diagonal signs, local
|
||||
if ( inI ) NegateCopy(Ubuf, Arows, col0+WI, WJ);
|
||||
if ( inJ ) NegateCopy(Tbuf, Arows, col0, WI);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// PUBLIC ENTRY. Arows: my rows of the rank-major N x N matrix (fp64).
|
||||
// On exit Arows holds my rows of the inverse, still fp64; the caller
|
||||
// owns the single terminal rounding into its fp32 apply storage.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
void Invert(BlockRows &Arows)
|
||||
{
|
||||
GRID_ASSERT( Arows.rows == myNrows );
|
||||
GRID_ASSERT( Arows.cols == N );
|
||||
|
||||
telNormB.resize(0);
|
||||
telSratio.resize(0);
|
||||
telLeafMaxInv = 0.0;
|
||||
|
||||
tMemset = 0.0;
|
||||
tDeposit = 0.0;
|
||||
tAllreduce = 0.0;
|
||||
tGemm = 0.0;
|
||||
tLeaf = 0.0;
|
||||
tARmin = 1.0e30;
|
||||
tARmax = 0.0;
|
||||
bytesAllreduce = 0;
|
||||
nAllreduce = 0;
|
||||
nGatherGemm = 0;
|
||||
|
||||
SchurNode(0, P, 0, N, Arows);
|
||||
|
||||
RealD mx = telLeafMaxInv;
|
||||
grid->GlobalMax(mx);
|
||||
telLeafMaxInv = mx;
|
||||
}
|
||||
|
||||
// All telemetry values are globally reduced or boss-local; safe to
|
||||
// stream on every rank (Grid quiesces stdout to the boss unless
|
||||
// --debug-stdout). NOTE: tAllreduce INCLUDES wait/imbalance -- a rank
|
||||
// arriving early books its wait here; the min/max spread across ranks
|
||||
// separates true wire time (~min) from skew (max-min).
|
||||
void ReportTelemetry(void)
|
||||
{
|
||||
for(uint64_t i=0; i<telNormB.size(); i++)
|
||||
{
|
||||
std::cout << GridLogPerformance
|
||||
<< "SchurNode " << i
|
||||
<< " ||B||_F " << telNormB[i]
|
||||
<< " ||S||/||A22|| " << telSratio[i]
|
||||
<< std::endl;
|
||||
}
|
||||
std::cout << GridLogPerformance
|
||||
<< "Schur leaves max|Ainv| " << telLeafMaxInv
|
||||
<< std::endl;
|
||||
|
||||
RealD armax = tAllreduce;
|
||||
RealD armin = -tAllreduce;
|
||||
grid->GlobalMax(armax);
|
||||
grid->GlobalMax(armin);
|
||||
armin = -armin;
|
||||
|
||||
std::cout << GridLogMessage << "Schur phases (boss rank, seconds):"
|
||||
<< " memset " << tMemset/1.0e6
|
||||
<< " deposit " << tDeposit/1.0e6
|
||||
<< " allreduce " << tAllreduce/1.0e6
|
||||
<< " gemm " << tGemm/1.0e6
|
||||
<< " leaf " << tLeaf/1.0e6
|
||||
<< std::endl;
|
||||
std::cout << GridLogMessage << "Schur comms:"
|
||||
<< " GatherGemm calls " << nGatherGemm
|
||||
<< " panel allreduces " << nAllreduce
|
||||
<< " allreduce GB " << bytesAllreduce/1024./1024./1024.
|
||||
<< " allreduce s min/max over ranks " << armin/1.0e6
|
||||
<< " / " << armax/1.0e6
|
||||
<< std::endl;
|
||||
std::cout << GridLogMessage << "Schur comms per-call (boss):"
|
||||
<< " min " << (nAllreduce ? tARmin/1.0e3 : 0.0) << " ms"
|
||||
<< " avg " << (nAllreduce ? tAllreduce/nAllreduce/1.0e3 : 0.0) << " ms"
|
||||
<< " max " << tARmax/1.0e3 << " ms"
|
||||
<< std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -63,10 +63,12 @@ void MemoryManager::PrintBytes(void)
|
||||
std::cout << " MemoryManager : "<<(total_device>>20)<<" accelerator Mbytes "<<std::endl;
|
||||
std::cout << " MemoryManager : "<<(total_host>>20) <<" cpu Mbytes "<<std::endl;
|
||||
uint64_t cacheBytes;
|
||||
cacheBytes = HostCacheBytes();
|
||||
std::cout << " MemoryManager : "<<(cacheBytes>>20) <<" cpu alloc cache Mbytes "<<std::endl;
|
||||
cacheBytes = DeviceCacheBytes();
|
||||
std::cout << " MemoryManager : "<<(cacheBytes>>20) <<" acc alloc cache Mbytes "<<std::endl;
|
||||
cacheBytes = CacheBytes[Cpu];
|
||||
std::cout << " MemoryManager : "<<(cacheBytes>>20) <<" cpu cache Mbytes "<<std::endl;
|
||||
cacheBytes = CacheBytes[Acc];
|
||||
std::cout << " MemoryManager : "<<(cacheBytes>>20) <<" acc cache Mbytes "<<std::endl;
|
||||
cacheBytes = CacheBytes[Shared];
|
||||
std::cout << " MemoryManager : "<<(cacheBytes>>20) <<" shared cache Mbytes "<<std::endl;
|
||||
|
||||
#ifdef GRID_CUDA
|
||||
cuda_mem();
|
||||
|
||||
@@ -113,7 +113,7 @@ private:
|
||||
static void *Insert(void *ptr,size_t bytes,AllocationCacheEntry *entries,int ncache,int &victim,uint64_t &cbytes) ;
|
||||
static void *Lookup(size_t bytes,AllocationCacheEntry *entries,int ncache,uint64_t &cbytes) ;
|
||||
|
||||
public:
|
||||
public:
|
||||
static void PrintBytes(void);
|
||||
static void Audit(std::string s);
|
||||
static void Init(void);
|
||||
@@ -215,7 +215,6 @@ public:
|
||||
static void NotifyDeletion(void * CpuPtr);
|
||||
static void Print(void);
|
||||
static void PrintAll(void);
|
||||
static void EvictAll(void);
|
||||
static void PrintState( void* CpuPtr);
|
||||
static int isOpen (void* CpuPtr);
|
||||
static void ViewClose(void* CpuPtr,ViewMode mode);
|
||||
|
||||
@@ -79,25 +79,6 @@ void MemoryManager::EntryErase(uint64_t CpuPtr)
|
||||
auto AccCache = EntryLookup(CpuPtr);
|
||||
AccViewTable.erase(CpuPtr);
|
||||
}
|
||||
/////////////////////////////////////////////////////////////////////////////////
|
||||
// LRU membership invariant:
|
||||
//
|
||||
// LRU_valid == 1 <=> AccPtr != NULL && accLock == 0 && cpuLock == 0
|
||||
//
|
||||
// i.e. the LRU queue contains exactly the device-resident, completely unlocked
|
||||
// entries -- the evictable set. Membership is maintained EAGERLY at the lock
|
||||
// 0<->1 edges, O(1) via the stored LRU_entry iterator:
|
||||
//
|
||||
// AcceleratorViewOpen lock 0->1 : LRUremove (gated on LRU_valid)
|
||||
// AcceleratorViewClose accLock->0: LRUinsert (AccPtr necessarily exists)
|
||||
// CpuViewOpen lock 0->1 : LRUremove (gated on LRU_valid)
|
||||
// CpuViewClose cpuLock->0: LRUinsert (iff AccPtr exists)
|
||||
// Evict/AccDiscard : LRUremove (frees the device copy)
|
||||
//
|
||||
// Consequences: victims taken from LRU.back() are evictable by construction;
|
||||
// Evict() on a locked entry is an invariant violation (asserted), and the
|
||||
// eviction loops (EvictVictims/EvictAll) cannot spin.
|
||||
/////////////////////////////////////////////////////////////////////////////////
|
||||
void MemoryManager::LRUinsert(AcceleratorViewEntry &AccCache)
|
||||
{
|
||||
GRID_ASSERT(AccCache.LRU_valid==0);
|
||||
@@ -149,21 +130,21 @@ void MemoryManager::Evict(AcceleratorViewEntry &AccCache)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Make CPU consistent, remove from Accelerator, remove from LRU, LEAVE CPU only entry
|
||||
// Cannot be locked. If allocated must be in LRU pool.
|
||||
// Cannot be acclocked. If allocated must be in LRU pool.
|
||||
//
|
||||
// (Historical: a Nov 2022 incident (two CpuPtrs; eviction called from
|
||||
// CpuViewOpen -- since excised) could present a cpuLocked entry here, and
|
||||
// silent-return guards were added. The LRU membership invariant (see
|
||||
// LRUinsert) now excludes ALL locked entries from the queue eagerly at the
|
||||
// lock edges, so a locked victim is an invariant violation: asserted.)
|
||||
// Nov 2022... Felix issue: Allocating two CpuPtrs, can have an entry in LRU-q with CPUlock.
|
||||
// and require to evict the AccPtr copy. Eviction was a mistake in CpuViewOpen
|
||||
// but there is a weakness where CpuLock entries are attempted for erase
|
||||
// Take these OUT LRU queue when CPU locked?
|
||||
// Cannot take out the table as cpuLock data is important.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
GRID_ASSERT(AccCache.state!=Empty);
|
||||
|
||||
mprintf("MemoryManager: Evict CpuPtr %lx AccPtr %lx cpuLock %ld accLock %ld",
|
||||
(uint64_t)AccCache.CpuPtr,(uint64_t)AccCache.AccPtr,
|
||||
(uint64_t)AccCache.cpuLock,(uint64_t)AccCache.accLock);
|
||||
GRID_ASSERT(AccCache.accLock==0);
|
||||
GRID_ASSERT(AccCache.cpuLock==0);
|
||||
if (AccCache.accLock!=0) return;
|
||||
if (AccCache.cpuLock!=0) return;
|
||||
if(AccCache.state==AccDirty) {
|
||||
Flush(AccCache);
|
||||
}
|
||||
@@ -269,19 +250,6 @@ void MemoryManager::EvictVictims(uint64_t bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
void MemoryManager::EvictAll(void)
|
||||
{
|
||||
while(LRU.size()>0){
|
||||
if ( DeviceLRUBytes > 0){
|
||||
uint64_t victim = LRU.back(); // From the LRU
|
||||
auto AccCacheIterator = EntryLookup(victim);
|
||||
auto & AccCache = AccCacheIterator->second;
|
||||
Evict(AccCache);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
uint64_t MemoryManager::AcceleratorViewOpen(uint64_t CpuPtr,size_t bytes,ViewMode mode,ViewAdvise hint)
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
@@ -415,13 +383,6 @@ void MemoryManager::CpuViewClose(uint64_t CpuPtr)
|
||||
GRID_ASSERT(AccCache.accLock==0);
|
||||
|
||||
AccCache.cpuLock--;
|
||||
// Return to LRU queue when fully unlocked -- mirrors AcceleratorViewClose.
|
||||
// Asymmetry vs the Acc side: a device copy need not exist for a host view;
|
||||
// only device-resident entries belong in the (evictable) LRU queue.
|
||||
if( (AccCache.cpuLock==0) && (AccCache.AccPtr!=(uint64_t)NULL) ) {
|
||||
dprintf("CpuViewClose %lx cpuLock decremented to zero, move to LRU queue",(uint64_t)CpuPtr);
|
||||
LRUinsert(AccCache);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Action State StateNext Flush Clone
|
||||
@@ -488,14 +449,6 @@ uint64_t MemoryManager::CpuViewOpen(uint64_t CpuPtr,size_t bytes,ViewMode mode,V
|
||||
GRID_ASSERT(0); // should be unreachable
|
||||
}
|
||||
|
||||
GRID_ASSERT(AccCache.cpuLock>0);
|
||||
// If view is opened on host must remove from LRU -- mirrors AcceleratorViewOpen.
|
||||
// LRU_valid==1 here implies this is the 0->1 lock edge of a device-resident entry.
|
||||
if(AccCache.LRU_valid==1){
|
||||
dprintf("CpuViewOpen: entry removed from LRU ");
|
||||
LRUremove(AccCache);
|
||||
}
|
||||
|
||||
AccCache.transient= transient? EvictNext : 0;
|
||||
|
||||
return AccCache.CpuPtr;
|
||||
|
||||
@@ -238,16 +238,6 @@ public:
|
||||
}
|
||||
void AllToAll(int dim ,void *in,void *out,uint64_t words,uint64_t bytes);
|
||||
void AllToAll(void *in,void *out,uint64_t words ,uint64_t bytes);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// Variable count all to all. Counts and displacements are in units of
|
||||
// "bytes" sized words and are indexed by rank within this communicator.
|
||||
// For exchanges that are a permutation but do not divide evenly between
|
||||
// ranks; AllToAll above is the uniform count special case.
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
void AllToAllV(void *in ,const std::vector<int> &sendcounts,const std::vector<int> &senddispls,
|
||||
void *out,const std::vector<int> &recvcounts,const std::vector<int> &recvdispls,
|
||||
uint64_t bytes);
|
||||
|
||||
template<class obj> void Broadcast(int root,obj &data)
|
||||
{
|
||||
|
||||
@@ -945,25 +945,5 @@ void CartesianCommunicator::AllToAll(void *in,void *out,uint64_t words,uint64_t
|
||||
MPI_Alltoall(in,iwords,object,out,iwords,object,communicator);
|
||||
MPI_Type_free(&object);
|
||||
}
|
||||
void CartesianCommunicator::AllToAllV(void *in ,const std::vector<int> &sendcounts,const std::vector<int> &senddispls,
|
||||
void *out,const std::vector<int> &recvcounts,const std::vector<int> &recvdispls,
|
||||
uint64_t bytes)
|
||||
{
|
||||
FlightRecorder::StepLog("AllToAllV");
|
||||
GRID_ASSERT(sendcounts.size()==(size_t)_Nprocessors);
|
||||
GRID_ASSERT(senddispls.size()==(size_t)_Nprocessors);
|
||||
GRID_ASSERT(recvcounts.size()==(size_t)_Nprocessors);
|
||||
GRID_ASSERT(recvdispls.size()==(size_t)_Nprocessors);
|
||||
// MPI counts are "int"; the caller sizes the word to keep them in range
|
||||
int ibytes = bytes;
|
||||
GRID_ASSERT(bytes == (uint64_t)ibytes);
|
||||
MPI_Datatype object;
|
||||
MPI_Type_contiguous(ibytes,MPI_BYTE,&object);
|
||||
MPI_Type_commit(&object);
|
||||
int ierr = MPI_Alltoallv(in ,(int *)&sendcounts[0],(int *)&senddispls[0],object,
|
||||
out,(int *)&recvcounts[0],(int *)&recvdispls[0],object,communicator);
|
||||
GRID_ASSERT(ierr==0);
|
||||
MPI_Type_free(&object);
|
||||
}
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -113,17 +113,6 @@ void CartesianCommunicator::AllToAll(void *in,void *out,uint64_t words,uint64_t
|
||||
{
|
||||
bcopy(in,out,bytes*words);
|
||||
}
|
||||
void CartesianCommunicator::AllToAllV(void *in ,const std::vector<int> &sendcounts,const std::vector<int> &senddispls,
|
||||
void *out,const std::vector<int> &recvcounts,const std::vector<int> &recvdispls,
|
||||
uint64_t bytes)
|
||||
{
|
||||
// Single rank: the exchange degenerates to a copy of our own segment
|
||||
GRID_ASSERT(sendcounts.size()==1);
|
||||
GRID_ASSERT(recvcounts.size()==1);
|
||||
GRID_ASSERT(sendcounts[0]==recvcounts[0]);
|
||||
bcopy((char *)in +(uint64_t)senddispls[0]*bytes,
|
||||
(char *)out+(uint64_t)recvdispls[0]*bytes,bytes*(uint64_t)sendcounts[0]);
|
||||
}
|
||||
|
||||
int CartesianCommunicator::RankWorld(void){return 0;}
|
||||
void CartesianCommunicator::Barrier(void){}
|
||||
|
||||
+2
-2
@@ -21895,7 +21895,7 @@ inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC
|
||||
/// @brief user-defined string literal for JSON values
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/
|
||||
JSON_HEDLEY_NON_NULL(1)
|
||||
inline nlohmann::json operator ""_json(const char* s, std::size_t n)
|
||||
inline nlohmann::json operator "" _json(const char* s, std::size_t n)
|
||||
{
|
||||
return nlohmann::json::parse(s, s + n);
|
||||
}
|
||||
@@ -21903,7 +21903,7 @@ inline nlohmann::json operator ""_json(const char* s, std::size_t n)
|
||||
/// @brief user-defined string literal for JSON pointer
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/
|
||||
JSON_HEDLEY_NON_NULL(1)
|
||||
inline nlohmann::json::json_pointer operator ""_json_pointer(const char* s, std::size_t n)
|
||||
inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
|
||||
{
|
||||
return nlohmann::json::json_pointer(std::string(s, n));
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ accelerator_inline vobj predicatedWhere(const iobj &predicate,
|
||||
|
||||
extract(iftrue, truevals);
|
||||
extract(iffalse, falsevals);
|
||||
extract(TensorRemove(predicate), mask);
|
||||
extract<vInteger, Integer>(TensorRemove(predicate), mask);
|
||||
|
||||
for (int s = 0; s < Nsimd; s++) {
|
||||
if (mask[s]) falsevals[s] = truevals[s];
|
||||
|
||||
@@ -289,7 +289,7 @@ public:
|
||||
///////////////////////////////////////////
|
||||
// move constructor
|
||||
///////////////////////////////////////////
|
||||
Lattice(Lattice && r) noexcept {
|
||||
Lattice(Lattice && r){
|
||||
this->_grid = r.Grid();
|
||||
this->_odata = r._odata;
|
||||
this->_odata_size = r._odata_size;
|
||||
@@ -330,7 +330,7 @@ public:
|
||||
///////////////////////////////////////////
|
||||
// Move assignment possible if same type
|
||||
///////////////////////////////////////////
|
||||
inline Lattice<vobj> & operator = (Lattice<vobj> && r) noexcept {
|
||||
inline Lattice<vobj> & operator = (Lattice<vobj> && r){
|
||||
|
||||
resize(0); // deletes if appropriate
|
||||
this->_grid = r.Grid();
|
||||
|
||||
@@ -40,16 +40,16 @@ NAMESPACE_BEGIN(Grid);
|
||||
//Query supporting logical &&, ||,
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
template<class vobj> using vPredicate = iScalar<IntegerPredicate<vobj> > ;
|
||||
typedef iScalar<vInteger> vPredicate ;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// compare lattice to lattice
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
template<class vfunctor,class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > LLComparison(vfunctor op,const Lattice<lobj> &lhs,const Lattice<robj> &rhs)
|
||||
inline Lattice<vPredicate> LLComparison(vfunctor op,const Lattice<lobj> &lhs,const Lattice<robj> &rhs)
|
||||
{
|
||||
Lattice<vPredicate<lobj> > ret(rhs.Grid());
|
||||
Lattice<vPredicate> ret(rhs.Grid());
|
||||
autoView( lhs_v, lhs, CpuRead);
|
||||
autoView( rhs_v, rhs, CpuRead);
|
||||
autoView( ret_v, ret, CpuWrite);
|
||||
@@ -62,9 +62,9 @@ inline Lattice<vPredicate<lobj> > LLComparison(vfunctor op,const Lattice<lobj> &
|
||||
// compare lattice to scalar
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
template<class vfunctor,class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > LSComparison(vfunctor op,const Lattice<lobj> &lhs,const robj &rhs)
|
||||
inline Lattice<vPredicate> LSComparison(vfunctor op,const Lattice<lobj> &lhs,const robj &rhs)
|
||||
{
|
||||
Lattice<vPredicate<lobj> > ret(lhs.Grid());
|
||||
Lattice<vPredicate> ret(lhs.Grid());
|
||||
autoView( lhs_v, lhs, CpuRead);
|
||||
autoView( ret_v, ret, CpuWrite);
|
||||
thread_for( ss, lhs_v.size(), {
|
||||
@@ -76,9 +76,9 @@ inline Lattice<vPredicate<lobj> > LSComparison(vfunctor op,const Lattice<lobj> &
|
||||
// compare scalar to lattice
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
template<class vfunctor,class lobj,class robj>
|
||||
inline Lattice<vPredicate<robj> > SLComparison(vfunctor op,const lobj &lhs,const Lattice<robj> &rhs)
|
||||
inline Lattice<vPredicate> SLComparison(vfunctor op,const lobj &lhs,const Lattice<robj> &rhs)
|
||||
{
|
||||
Lattice<vPredicate<robj> > ret(rhs.Grid());
|
||||
Lattice<vPredicate> ret(rhs.Grid());
|
||||
autoView( rhs_v, rhs, CpuRead);
|
||||
autoView( ret_v, ret, CpuWrite);
|
||||
thread_for( ss, rhs_v.size(), {
|
||||
@@ -92,87 +92,87 @@ inline Lattice<vPredicate<robj> > SLComparison(vfunctor op,const lobj &lhs,const
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Less than
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator < (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator < (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
return LLComparison(vlt<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator < (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
inline Lattice<vPredicate> operator < (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
return LSComparison(vlt<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<robj> > operator < (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator < (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
return SLComparison(vlt<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
|
||||
// Less than equal
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator <= (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator <= (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
return LLComparison(vle<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator <= (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
inline Lattice<vPredicate> operator <= (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
return LSComparison(vle<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<robj> > operator <= (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator <= (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
return SLComparison(vle<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
|
||||
// Greater than
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator > (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator > (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
return LLComparison(vgt<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator > (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
inline Lattice<vPredicate> operator > (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
return LSComparison(vgt<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<robj> > operator > (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator > (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
return SLComparison(vgt<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
|
||||
|
||||
// Greater than equal
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator >= (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator >= (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
return LLComparison(vge<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator >= (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
inline Lattice<vPredicate> operator >= (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
return LSComparison(vge<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<robj> > operator >= (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator >= (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
return SLComparison(vge<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
|
||||
// equal
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator == (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator == (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
return LLComparison(veq<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator == (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
inline Lattice<vPredicate> operator == (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
return LSComparison(veq<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<robj> > operator == (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator == (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
return SLComparison(veq<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
|
||||
|
||||
// not equal
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator != (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator != (const Lattice<lobj> & lhs, const Lattice<robj> & rhs) {
|
||||
return LLComparison(vne<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<lobj> > operator != (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
inline Lattice<vPredicate> operator != (const Lattice<lobj> & lhs, const robj & rhs) {
|
||||
return LSComparison(vne<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
template<class lobj,class robj>
|
||||
inline Lattice<vPredicate<robj> > operator != (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
inline Lattice<vPredicate> operator != (const lobj & lhs, const Lattice<robj> & rhs) {
|
||||
return SLComparison(vne<lobj,robj>(),lhs,rhs);
|
||||
}
|
||||
NAMESPACE_END(Grid);
|
||||
|
||||
@@ -39,53 +39,47 @@ NAMESPACE_BEGIN(Grid);
|
||||
//
|
||||
// Should guard this with isGridTensor<> enable if?
|
||||
/////////////////////////////////////////
|
||||
//
|
||||
// Predicate type matching the operand's vectorisation
|
||||
//
|
||||
template<class obj> using IntegerPredicate =
|
||||
typename GridTypeMapper<typename GridTypeMapper<obj>::vector_type>::Integerified;
|
||||
|
||||
//
|
||||
// Generic list of functors
|
||||
//
|
||||
template<class lobj,class robj> class veq {
|
||||
public:
|
||||
accelerator IntegerPredicate<lobj> operator()(const lobj &lhs, const robj &rhs)
|
||||
accelerator vInteger operator()(const lobj &lhs, const robj &rhs)
|
||||
{
|
||||
return (lhs) == (rhs);
|
||||
}
|
||||
};
|
||||
template<class lobj,class robj> class vne {
|
||||
public:
|
||||
accelerator IntegerPredicate<lobj> operator()(const lobj &lhs, const robj &rhs)
|
||||
accelerator vInteger operator()(const lobj &lhs, const robj &rhs)
|
||||
{
|
||||
return (lhs) != (rhs);
|
||||
}
|
||||
};
|
||||
template<class lobj,class robj> class vlt {
|
||||
public:
|
||||
accelerator IntegerPredicate<lobj> operator()(const lobj &lhs, const robj &rhs)
|
||||
accelerator vInteger operator()(const lobj &lhs, const robj &rhs)
|
||||
{
|
||||
return (lhs) < (rhs);
|
||||
}
|
||||
};
|
||||
template<class lobj,class robj> class vle {
|
||||
public:
|
||||
accelerator IntegerPredicate<lobj> operator()(const lobj &lhs, const robj &rhs)
|
||||
accelerator vInteger operator()(const lobj &lhs, const robj &rhs)
|
||||
{
|
||||
return (lhs) <= (rhs);
|
||||
}
|
||||
};
|
||||
template<class lobj,class robj> class vgt {
|
||||
public:
|
||||
accelerator IntegerPredicate<lobj> operator()(const lobj &lhs, const robj &rhs)
|
||||
accelerator vInteger operator()(const lobj &lhs, const robj &rhs)
|
||||
{
|
||||
return (lhs) > (rhs);
|
||||
}
|
||||
};
|
||||
template<class lobj,class robj> class vge {
|
||||
public:
|
||||
accelerator IntegerPredicate<lobj> operator()(const lobj &lhs, const robj &rhs)
|
||||
accelerator vInteger operator()(const lobj &lhs, const robj &rhs)
|
||||
{
|
||||
return (lhs) >= (rhs);
|
||||
}
|
||||
@@ -139,78 +133,78 @@ NAMESPACE_BEGIN(Grid);
|
||||
// Integer and real get extra relational functions.
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
template<class sfunctor, class vsimd,IfNotComplex<vsimd> = 0>
|
||||
accelerator_inline IntegerPredicate<vsimd> Comparison(sfunctor sop,const vsimd & lhs, const vsimd & rhs)
|
||||
accelerator_inline vInteger Comparison(sfunctor sop,const vsimd & lhs, const vsimd & rhs)
|
||||
{
|
||||
typedef typename vsimd::scalar_type scalar;
|
||||
ExtractBuffer<scalar> vlhs(vsimd::Nsimd()); // Use functors to reduce this to single implementation
|
||||
ExtractBuffer<scalar> vrhs(vsimd::Nsimd());
|
||||
ExtractBuffer<Integer> vpred(vsimd::Nsimd());
|
||||
IntegerPredicate<vsimd> ret;
|
||||
vInteger ret;
|
||||
extract<vsimd,scalar>(lhs,vlhs);
|
||||
extract<vsimd,scalar>(rhs,vrhs);
|
||||
for(int s=0;s<vsimd::Nsimd();s++){
|
||||
vpred[s] = sop(vlhs[s],vrhs[s]);
|
||||
}
|
||||
merge<IntegerPredicate<vsimd>,Integer>(ret,vpred);
|
||||
merge<vInteger,Integer>(ret,vpred);
|
||||
return ret;
|
||||
}
|
||||
|
||||
template<class sfunctor, class vsimd,IfNotComplex<vsimd> = 0>
|
||||
accelerator_inline IntegerPredicate<vsimd> Comparison(sfunctor sop,const vsimd & lhs, const typename vsimd::scalar_type & rhs)
|
||||
accelerator_inline vInteger Comparison(sfunctor sop,const vsimd & lhs, const typename vsimd::scalar_type & rhs)
|
||||
{
|
||||
typedef typename vsimd::scalar_type scalar;
|
||||
ExtractBuffer<scalar> vlhs(vsimd::Nsimd()); // Use functors to reduce this to single implementation
|
||||
ExtractBuffer<Integer> vpred(vsimd::Nsimd());
|
||||
IntegerPredicate<vsimd> ret;
|
||||
vInteger ret;
|
||||
extract<vsimd,scalar>(lhs,vlhs);
|
||||
for(int s=0;s<vsimd::Nsimd();s++){
|
||||
vpred[s] = sop(vlhs[s],rhs);
|
||||
}
|
||||
merge<IntegerPredicate<vsimd>,Integer>(ret,vpred);
|
||||
merge<vInteger,Integer>(ret,vpred);
|
||||
return ret;
|
||||
}
|
||||
|
||||
template<class sfunctor, class vsimd,IfNotComplex<vsimd> = 0>
|
||||
accelerator_inline IntegerPredicate<vsimd> Comparison(sfunctor sop,const typename vsimd::scalar_type & lhs, const vsimd & rhs)
|
||||
accelerator_inline vInteger Comparison(sfunctor sop,const typename vsimd::scalar_type & lhs, const vsimd & rhs)
|
||||
{
|
||||
typedef typename vsimd::scalar_type scalar;
|
||||
ExtractBuffer<scalar> vrhs(vsimd::Nsimd()); // Use functors to reduce this to single implementation
|
||||
ExtractBuffer<Integer> vpred(vsimd::Nsimd());
|
||||
IntegerPredicate<vsimd> ret;
|
||||
vInteger ret;
|
||||
extract<vsimd,scalar>(rhs,vrhs);
|
||||
for(int s=0;s<vsimd::Nsimd();s++){
|
||||
vpred[s] = sop(lhs,vrhs[s]);
|
||||
}
|
||||
merge<IntegerPredicate<vsimd>,Integer>(ret,vpred);
|
||||
merge<vInteger,Integer>(ret,vpred);
|
||||
return ret;
|
||||
}
|
||||
|
||||
#define DECLARE_RELATIONAL_EQ(op,functor) \
|
||||
template<class vsimd,IfSimd<vsimd> = 0>\
|
||||
accelerator_inline IntegerPredicate<vsimd> operator op (const vsimd & lhs, const vsimd & rhs)\
|
||||
accelerator_inline vInteger operator op (const vsimd & lhs, const vsimd & rhs)\
|
||||
{\
|
||||
typedef typename vsimd::scalar_type scalar;\
|
||||
return Comparison(functor<scalar,scalar>(),lhs,rhs);\
|
||||
}\
|
||||
template<class vsimd,IfSimd<vsimd> = 0>\
|
||||
accelerator_inline IntegerPredicate<vsimd> operator op (const vsimd & lhs, const typename vsimd::scalar_type & rhs) \
|
||||
accelerator_inline vInteger operator op (const vsimd & lhs, const typename vsimd::scalar_type & rhs) \
|
||||
{\
|
||||
typedef typename vsimd::scalar_type scalar;\
|
||||
return Comparison(functor<scalar,scalar>(),lhs,rhs);\
|
||||
}\
|
||||
template<class vsimd,IfSimd<vsimd> = 0>\
|
||||
accelerator_inline IntegerPredicate<vsimd> operator op (const typename vsimd::scalar_type & lhs, const vsimd & rhs) \
|
||||
accelerator_inline vInteger operator op (const typename vsimd::scalar_type & lhs, const vsimd & rhs) \
|
||||
{\
|
||||
typedef typename vsimd::scalar_type scalar;\
|
||||
return Comparison(functor<scalar,scalar>(),lhs,rhs);\
|
||||
}\
|
||||
template<class vsimd>\
|
||||
accelerator_inline IntegerPredicate<vsimd> operator op(const iScalar<vsimd> &lhs,const typename vsimd::scalar_type &rhs) \
|
||||
accelerator_inline vInteger operator op(const iScalar<vsimd> &lhs,const typename vsimd::scalar_type &rhs) \
|
||||
{ \
|
||||
return lhs._internal op rhs; \
|
||||
} \
|
||||
template<class vsimd>\
|
||||
accelerator_inline IntegerPredicate<vsimd> operator op(const typename vsimd::scalar_type &lhs,const iScalar<vsimd> &rhs) \
|
||||
accelerator_inline vInteger operator op(const typename vsimd::scalar_type &lhs,const iScalar<vsimd> &rhs) \
|
||||
{ \
|
||||
return lhs op rhs._internal; \
|
||||
} \
|
||||
@@ -218,7 +212,7 @@ NAMESPACE_BEGIN(Grid);
|
||||
#define DECLARE_RELATIONAL(op,functor) \
|
||||
DECLARE_RELATIONAL_EQ(op,functor) \
|
||||
template<class vsimd>\
|
||||
accelerator_inline IntegerPredicate<vsimd> operator op(const iScalar<vsimd> &lhs,const iScalar<vsimd> &rhs)\
|
||||
accelerator_inline vInteger operator op(const iScalar<vsimd> &lhs,const iScalar<vsimd> &rhs)\
|
||||
{ \
|
||||
return lhs._internal op rhs._internal; \
|
||||
}
|
||||
|
||||
@@ -197,15 +197,12 @@ __global__ void reduceKernel(const vobj *lat, sobj *buffer, Iterator n) {
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Possibly promote to double and sum
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#undef GRID_REDUCTION_TIMING
|
||||
|
||||
template <class vobj>
|
||||
inline typename vobj::scalar_objectD sumD_gpu_small(const vobj *lat, Integer osites)
|
||||
inline typename vobj::scalar_objectD sumD_gpu_small(const vobj *lat, Integer osites)
|
||||
{
|
||||
typedef typename vobj::scalar_objectD sobj;
|
||||
typedef decltype(lat) Iterator;
|
||||
|
||||
|
||||
Integer nsimd= vobj::Nsimd();
|
||||
Integer size = osites*nsimd;
|
||||
|
||||
@@ -214,188 +211,41 @@ inline typename vobj::scalar_objectD sumD_gpu_small(const vobj *lat, Integer osi
|
||||
GRID_ASSERT(ok);
|
||||
|
||||
Integer smemSize = numThreads * sizeof(sobj);
|
||||
// Move out of UVM
|
||||
// Turns out I had messed up the synchronise after move to compute stream
|
||||
// as running this on the default stream fools the synchronise
|
||||
deviceVector<sobj> buffer(numBlocks);
|
||||
sobj *buffer_v = &buffer[0];
|
||||
sobj result;
|
||||
|
||||
#ifdef GRID_REDUCTION_TIMING
|
||||
RealD t_kernel = -usecond();
|
||||
#endif
|
||||
reduceKernel<<< numBlocks, numThreads, smemSize, computeStream >>>(lat, buffer_v, size);
|
||||
accelerator_barrier();
|
||||
#ifdef GRID_REDUCTION_TIMING
|
||||
t_kernel += usecond();
|
||||
RealD t_d2h = -usecond();
|
||||
#endif
|
||||
acceleratorCopyFromDevice(buffer_v,&result,sizeof(result));
|
||||
#ifdef GRID_REDUCTION_TIMING
|
||||
t_d2h += usecond();
|
||||
std::cout << GridLogDebug << " sumD_gpu_small"
|
||||
<< " sizeof(sobj)=" << sizeof(sobj)
|
||||
<< " blocks=" << numBlocks << " threads=" << numThreads
|
||||
<< " kernel+barrier=" << t_kernel << " us"
|
||||
<< " D2H=" << t_d2h << " us" << std::endl;
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
|
||||
// Fused pack+reduce: reads R words of each vobj at word offset 'base',
|
||||
// accumulates directly into iVector<iScalar<scalarD>,R> without staging
|
||||
// through an intermediate bundle buffer. One HBM pass instead of three.
|
||||
template <int R, class vobj, class sobj, class Iterator>
|
||||
__device__ void packReduceBlocks(
|
||||
const iScalar<typename vobj::vector_type> *idat,
|
||||
sobj *g_odata, Iterator osites, int base, int words)
|
||||
{
|
||||
constexpr Iterator nsimd = vobj::Nsimd();
|
||||
Iterator blockSize = blockDim.x;
|
||||
|
||||
extern __shared__ __align__(COALESCE_GRANULARITY) unsigned char shmem_pointer[];
|
||||
sobj *sdata = (sobj *)shmem_pointer;
|
||||
|
||||
Iterator tid = threadIdx.x;
|
||||
Iterator i = blockIdx.x * (blockSize * 2) + threadIdx.x;
|
||||
Iterator gridSize = blockSize * 2 * gridDim.x;
|
||||
sobj mySum = Zero();
|
||||
|
||||
while (i < osites * nsimd) {
|
||||
Iterator lane = i % nsimd;
|
||||
Iterator ss = i / nsimd;
|
||||
sobj tmpD; zeroit(tmpD);
|
||||
for (int k = 0; k < R; k++) {
|
||||
auto w = extractLane(lane, idat[ss * words + base + k]);
|
||||
iScalar<typename vobj::scalar_typeD> wd; wd = w;
|
||||
tmpD._internal[k] = wd;
|
||||
}
|
||||
mySum += tmpD;
|
||||
|
||||
if (i + blockSize < osites * nsimd) {
|
||||
lane = (i + blockSize) % nsimd;
|
||||
ss = (i + blockSize) / nsimd;
|
||||
sobj tmpD2; zeroit(tmpD2);
|
||||
for (int k = 0; k < R; k++) {
|
||||
auto w = extractLane(lane, idat[ss * words + base + k]);
|
||||
iScalar<typename vobj::scalar_typeD> wd; wd = w;
|
||||
tmpD2._internal[k] = wd;
|
||||
}
|
||||
mySum += tmpD2;
|
||||
}
|
||||
i += gridSize;
|
||||
}
|
||||
|
||||
reduceBlock(sdata, mySum, tid);
|
||||
if (tid == 0) g_odata[blockIdx.x] = sdata[0];
|
||||
}
|
||||
|
||||
template <int R, class vobj, class sobj, class Iterator>
|
||||
__global__ void packReduceKernel(
|
||||
const iScalar<typename vobj::vector_type> *idat,
|
||||
sobj *buffer, Iterator osites, int base, int words)
|
||||
{
|
||||
Iterator blockSize = blockDim.x;
|
||||
|
||||
packReduceBlocks<R, vobj, sobj>(idat, buffer, osites, base, words);
|
||||
|
||||
if (gridDim.x > 1) {
|
||||
const Iterator tid = threadIdx.x;
|
||||
__shared__ bool amLast;
|
||||
extern __shared__ __align__(COALESCE_GRANULARITY) unsigned char shmem_pointer[];
|
||||
sobj *smem = (sobj *)shmem_pointer;
|
||||
|
||||
acceleratorFence();
|
||||
|
||||
if (tid == 0) {
|
||||
unsigned int ticket = atomicInc(&retirementCount, gridDim.x);
|
||||
amLast = (ticket == gridDim.x - 1);
|
||||
}
|
||||
acceleratorSynchroniseAll();
|
||||
|
||||
if (amLast) {
|
||||
Iterator i = tid;
|
||||
sobj mySum = Zero();
|
||||
while (i < (Iterator)gridDim.x) {
|
||||
mySum += buffer[i];
|
||||
i += blockSize;
|
||||
}
|
||||
reduceBlock(smem, mySum, tid);
|
||||
if (tid == 0) {
|
||||
buffer[0] = smem[0];
|
||||
retirementCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<int R, class vobj>
|
||||
inline void sumD_gpu_reduce_words(const vobj *lat, Integer osites,
|
||||
typename vobj::scalar_typeD *ret_p, int base)
|
||||
{
|
||||
typedef typename vobj::vector_type vector;
|
||||
typedef typename vobj::scalar_typeD scalarD;
|
||||
using BundleScalarD = iVector<iScalar<scalarD>, R>;
|
||||
|
||||
constexpr int Nsimd = vobj::Nsimd();
|
||||
const int words = sizeof(vobj) / sizeof(vector);
|
||||
const iScalar<vector> *idat = (const iScalar<vector> *)lat;
|
||||
|
||||
Integer size = (Integer)osites * Nsimd;
|
||||
Integer numThreads, numBlocks;
|
||||
int ok = getNumBlocksAndThreads(size, sizeof(BundleScalarD), numThreads, numBlocks);
|
||||
GRID_ASSERT(ok);
|
||||
|
||||
Integer smemSize = numThreads * sizeof(BundleScalarD);
|
||||
deviceVector<BundleScalarD> buffer(numBlocks);
|
||||
BundleScalarD *buffer_v = &buffer[0];
|
||||
BundleScalarD result;
|
||||
|
||||
#ifdef GRID_REDUCTION_TIMING
|
||||
RealD t_kernel = -usecond();
|
||||
#endif
|
||||
packReduceKernel<R, vobj, BundleScalarD, Integer>
|
||||
<<<numBlocks, numThreads, smemSize, computeStream>>>
|
||||
(idat, buffer_v, osites, base, words);
|
||||
accelerator_barrier();
|
||||
#ifdef GRID_REDUCTION_TIMING
|
||||
t_kernel += usecond();
|
||||
RealD t_d2h = -usecond();
|
||||
#endif
|
||||
acceleratorCopyFromDevice(buffer_v, &result, sizeof(result));
|
||||
#ifdef GRID_REDUCTION_TIMING
|
||||
t_d2h += usecond();
|
||||
std::cout << GridLogDebug << " sumD_gpu_reduce_words R=" << R
|
||||
<< " base=" << base
|
||||
<< " kernel=" << t_kernel << " D2H=" << t_d2h << " us" << std::endl;
|
||||
#endif
|
||||
|
||||
for (int k = 0; k < R; k++)
|
||||
ret_p[base + k] = TensorRemove(result._internal[k]);
|
||||
}
|
||||
|
||||
template <class vobj>
|
||||
inline typename vobj::scalar_objectD sumD_gpu_large(const vobj *lat, Integer osites)
|
||||
{
|
||||
typedef typename vobj::vector_type vector;
|
||||
typedef typename vobj::scalar_typeD scalarD;
|
||||
typedef typename vobj::scalar_objectD sobjD;
|
||||
|
||||
const int words = sizeof(vobj) / sizeof(vector);
|
||||
sobjD ret; zeroit(ret);
|
||||
typedef typename vobj::vector_type vector;
|
||||
typedef typename vobj::scalar_typeD scalarD;
|
||||
typedef typename vobj::scalar_objectD sobj;
|
||||
sobj ret;
|
||||
scalarD *ret_p = (scalarD *)&ret;
|
||||
|
||||
const int words = sizeof(vobj)/sizeof(vector);
|
||||
|
||||
#ifdef GRID_REDUCTION_TIMING
|
||||
RealD t_large = -usecond();
|
||||
#endif
|
||||
int w = 0;
|
||||
while (w + 12 <= words) { sumD_gpu_reduce_words<12>(lat, osites, ret_p, w); w += 12; }
|
||||
while (w + 4 <= words) { sumD_gpu_reduce_words< 4>(lat, osites, ret_p, w); w += 4; }
|
||||
while (w < words) { sumD_gpu_reduce_words< 1>(lat, osites, ret_p, w); w += 1; }
|
||||
#ifdef GRID_REDUCTION_TIMING
|
||||
t_large += usecond();
|
||||
std::cout << GridLogDebug << "sumD_gpu_large"
|
||||
<< " sizeof(sobjD)=" << sizeof(sobjD)
|
||||
<< " words=" << words << " total=" << t_large << " us" << std::endl;
|
||||
#endif
|
||||
deviceVector<vector> buffer(osites);
|
||||
vector *dat = (vector *)lat;
|
||||
vector *buf = &buffer[0];
|
||||
iScalar<vector> *tbuf =(iScalar<vector> *) &buffer[0];
|
||||
for(int w=0;w<words;w++) {
|
||||
|
||||
accelerator_for(ss,osites,1,{
|
||||
buf[ss] = dat[ss*words+w];
|
||||
});
|
||||
|
||||
ret_p[w] = sumD_gpu_small(tbuf,osites);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -438,11 +288,5 @@ inline typename vobj::scalar_object sum_gpu_large(const vobj *lat, Integer osite
|
||||
result = sumD_gpu_large(lat,osites);
|
||||
return result;
|
||||
}
|
||||
template<class Word> Word checksum_gpu(Word *vec,uint64_t L)
|
||||
{
|
||||
Word w;
|
||||
bzero(&w,sizeof(w));
|
||||
return w;
|
||||
}
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -6,27 +6,28 @@ NAMESPACE_BEGIN(Grid);
|
||||
|
||||
|
||||
template <class vobj>
|
||||
inline typename vobj::scalar_objectD sumD_gpu_tensor(const vobj *lat, Integer osites)
|
||||
inline typename vobj::scalar_objectD sumD_gpu_tensor(const vobj *lat, Integer osites)
|
||||
{
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
typedef typename vobj::scalar_objectD sobjD;
|
||||
|
||||
sobjD identity; zeroit(identity);
|
||||
sobjD ret; zeroit(ret);
|
||||
{
|
||||
sycl::buffer<sobjD, 1> abuff(&ret, {1});
|
||||
sobj identity; zeroit(identity);
|
||||
sobj ret; zeroit(ret);
|
||||
Integer nsimd= vobj::Nsimd();
|
||||
{
|
||||
sycl::buffer<sobj, 1> abuff(&ret, {1});
|
||||
theGridAccelerator->submit([&](sycl::handler &cgh) {
|
||||
auto Reduction = sycl::reduction(abuff, cgh, identity, std::plus<>());
|
||||
cgh.parallel_for(sycl::range<1>{(size_t)osites},
|
||||
Reduction,
|
||||
[=](sycl::id<1> item, auto &sum) {
|
||||
sobj s = Reduce(lat[item[0]]);
|
||||
sobjD sd; sd = s;
|
||||
sum += sd;
|
||||
});
|
||||
auto Reduction = sycl::reduction(abuff,cgh,identity,std::plus<>());
|
||||
cgh.parallel_for(sycl::range<1>{osites},
|
||||
Reduction,
|
||||
[=] (sycl::id<1> item, auto &sum) {
|
||||
auto osite = item[0];
|
||||
sum +=Reduce(lat[osite]);
|
||||
});
|
||||
});
|
||||
}
|
||||
return ret;
|
||||
sobjD dret; convertType(dret,ret);
|
||||
return dret;
|
||||
}
|
||||
|
||||
template <class vobj>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(GRID_CUDA)
|
||||
|
||||
#include <cub/cub.cuh>
|
||||
#define gpucub cub
|
||||
#define gpuError_t cudaError_t
|
||||
@@ -56,13 +57,8 @@ inline void sliceSumReduction_cub_small(const vobj *Data,
|
||||
//copy offsets to device
|
||||
acceleratorCopyToDeviceAsynch(&offsets[0],d_offsets,sizeof(int)*(rd+1),computeStream);
|
||||
|
||||
#if defined(__CUDACC__) && (__CUDACC_VER_MAJOR__ >= 13)
|
||||
#define GRID_CUB_SUM_OP ::cuda::std::plus<>{}
|
||||
#else
|
||||
#define GRID_CUB_SUM_OP ::gpucub::Sum()
|
||||
#endif
|
||||
|
||||
gpuError_t gpuErr = gpucub::DeviceSegmentedReduce::Reduce(temp_storage_array, temp_storage_bytes, rb_p,d_out, rd, d_offsets, d_offsets+1, GRID_CUB_SUM_OP, zero_init, computeStream);
|
||||
gpuError_t gpuErr = gpucub::DeviceSegmentedReduce::Reduce(temp_storage_array, temp_storage_bytes, rb_p,d_out, rd, d_offsets, d_offsets+1, ::gpucub::Sum(), zero_init, computeStream);
|
||||
if (gpuErr!=gpuSuccess) {
|
||||
std::cout << GridLogError << "Lattice_slicesum_gpu.h: Encountered error during gpucub::DeviceSegmentedReduce::Reduce (setup)! Error: " << gpuErr <<std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
@@ -86,13 +82,11 @@ inline void sliceSumReduction_cub_small(const vobj *Data,
|
||||
});
|
||||
|
||||
//issue segmented reductions in computeStream
|
||||
gpuErr = gpucub::DeviceSegmentedReduce::Reduce(temp_storage_array, temp_storage_bytes, rb_p, d_out, rd, d_offsets, d_offsets+1, GRID_CUB_SUM_OP, zero_init, computeStream);
|
||||
gpuErr = gpucub::DeviceSegmentedReduce::Reduce(temp_storage_array, temp_storage_bytes, rb_p, d_out, rd, d_offsets, d_offsets+1,::gpucub::Sum(), zero_init, computeStream);
|
||||
if (gpuErr!=gpuSuccess) {
|
||||
std::cout << GridLogError << "Lattice_slicesum_gpu.h: Encountered error during gpucub::DeviceSegmentedReduce::Reduce! Error: " << gpuErr <<std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
#undef GRID_CUB_SUM_OP
|
||||
|
||||
acceleratorCopyFromDeviceAsynch(d_out,&lvSum[0],rd*sizeof(vobj),computeStream);
|
||||
|
||||
|
||||
@@ -124,68 +124,6 @@ Lattice<iScalar<iScalar<iMatrix<vComplexD, N> > > > Inverse(const Lattice<iScala
|
||||
return ret;
|
||||
}
|
||||
|
||||
template<int N>
|
||||
Lattice<iMatrix<iScalar<iScalar<iScalar<vComplexD> > > , N> > Inverse(const Lattice<iMatrix<iScalar<iScalar<iScalar<vComplexD> > >, N> > &Umu)
|
||||
{
|
||||
GridBase *grid=Umu.Grid();
|
||||
auto lvol = grid->lSites();
|
||||
Lattice<iMatrix<iScalar<iScalar<iScalar<vComplexD> > >, N > > ret(grid);
|
||||
|
||||
autoView(Umu_v,Umu,CpuRead);
|
||||
autoView(ret_v,ret,CpuWrite);
|
||||
thread_for(site,lvol,{
|
||||
Eigen::MatrixXcd EigenU = Eigen::MatrixXcd::Zero(N,N);
|
||||
Coordinate lcoor;
|
||||
grid->LocalIndexToLocalCoor(site, lcoor);
|
||||
iMatrix<iScalar<iScalar<iScalar<ComplexD> > >, N > Us;
|
||||
iMatrix<iScalar<iScalar<iScalar<ComplexD> > >, N > Ui;
|
||||
peekLocalSite(Us, Umu_v, lcoor);
|
||||
for(int i=0;i<N;i++){
|
||||
for(int j=0;j<N;j++){
|
||||
EigenU(i,j) = Us(i,j)()()();
|
||||
}}
|
||||
Eigen::MatrixXcd EigenUinv = EigenU.inverse();
|
||||
for(int i=0;i<N;i++){
|
||||
for(int j=0;j<N;j++){
|
||||
Ui(i,j)()()() = EigenUinv(i,j);
|
||||
}}
|
||||
pokeLocalSite(Ui,ret_v,lcoor);
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
|
||||
template<int N>
|
||||
Lattice<iMatrix<iScalar<iScalar<iScalar<iScalar<vComplexD> > > > , N> > Inverse(const Lattice<iMatrix<iScalar<iScalar<iScalar<iScalar<vComplexD> > > >, N> > &Umu)
|
||||
{
|
||||
GridBase *grid=Umu.Grid();
|
||||
auto lvol = grid->lSites();
|
||||
Lattice<iMatrix<iScalar<iScalar<iScalar<iScalar<vComplexD> > > >, N > > ret(grid);
|
||||
|
||||
autoView(Umu_v,Umu,CpuRead);
|
||||
autoView(ret_v,ret,CpuWrite);
|
||||
thread_for(site,lvol,{
|
||||
Eigen::MatrixXcd EigenU = Eigen::MatrixXcd::Zero(N,N);
|
||||
Coordinate lcoor;
|
||||
grid->LocalIndexToLocalCoor(site, lcoor);
|
||||
iMatrix<iScalar<iScalar<iScalar<iScalar<ComplexD> > > >, N > Us;
|
||||
iMatrix<iScalar<iScalar<iScalar<iScalar<ComplexD> > > >, N > Ui;
|
||||
peekLocalSite(Us, Umu_v, lcoor);
|
||||
for(int i=0;i<N;i++){
|
||||
for(int j=0;j<N;j++){
|
||||
EigenU(i,j) = Us(i,j)()()()();
|
||||
}}
|
||||
Eigen::MatrixXcd EigenUinv = EigenU.inverse();
|
||||
for(int i=0;i<N;i++){
|
||||
for(int j=0;j<N;j++){
|
||||
Ui(i,j)()()()() = EigenUinv(i,j);
|
||||
}}
|
||||
pokeLocalSite(Ui,ret_v,lcoor);
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
#endif
|
||||
|
||||
@@ -2,7 +2,3 @@
|
||||
|
||||
int Grid::BinaryIO::latticeWriteMaxRetry = -1;
|
||||
Grid::BinaryIO::IoPerf Grid::BinaryIO::lastPerf;
|
||||
|
||||
// Target size of a single contiguous file extent under BINARYIO_AGGREGATE.
|
||||
// 4MB is around the knee for Lustre; exposed so it can be swept at runtime.
|
||||
uint64_t Grid::BinaryIO::aggregateTargetBytes = 4*1024*1024;
|
||||
+12
-463
@@ -39,7 +39,6 @@
|
||||
#endif
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/stat.h>
|
||||
#include <algorithm>
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
@@ -88,7 +87,6 @@ class BinaryIO {
|
||||
|
||||
static IoPerf lastPerf;
|
||||
static int latticeWriteMaxRetry;
|
||||
static uint64_t aggregateTargetBytes;
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// more byte manipulation helpers
|
||||
@@ -255,402 +253,12 @@ class BinaryIO {
|
||||
// Read or Write distributed lexico array of ANY object to a specific location in file
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
static const int BINARYIO_AGGREGATE = 0x20;
|
||||
static const int BINARYIO_MASTER_APPEND = 0x10;
|
||||
static const int BINARYIO_UNORDERED = 0x08;
|
||||
static const int BINARYIO_LEXICOGRAPHIC = 0x04;
|
||||
static const int BINARYIO_READ = 0x02;
|
||||
static const int BINARYIO_WRITE = 0x01;
|
||||
|
||||
// Single point of control for the aggregated path. Setting
|
||||
// GRID_BINARYIO_NOAGGREGATE falls back to plain lexicographic I/O.
|
||||
static int DefaultControl(void)
|
||||
{
|
||||
static int ctrl = getenv("GRID_BINARYIO_NOAGGREGATE")
|
||||
? BINARYIO_LEXICOGRAPHIC
|
||||
: BINARYIO_LEXICOGRAPHIC|BINARYIO_AGGREGATE;
|
||||
return ctrl;
|
||||
}
|
||||
|
||||
#ifdef USE_MPI_IO
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// Aggregation: self controlled transposition onto an I/O friendly layout.
|
||||
//
|
||||
// Under BINARYIO_LEXICOGRAPHIC the subarray file view handed to MPI-IO has
|
||||
// contiguous runs of only lLattice[0]*sizeof(fobj) bytes -- a few KB for
|
||||
// typical local volumes. Rather than rely on collective buffering to repair
|
||||
// that, redistribute the payload ourselves so every rank owns a contiguous
|
||||
// range of the global lexicographic site ordering, then issue large plain
|
||||
// contiguous writes.
|
||||
//
|
||||
// "Un-splitting" the nunsplit fastest dimensions means the row of ranks
|
||||
// sharing the remaining process coordinates collectively owns whole global
|
||||
// hyperplanes. All data movement is then confined to that row communicator.
|
||||
// Every rank still owns exactly lSites() sites afterwards, so the exchange is
|
||||
// a pure permutation and needs no divisibility condition on the process grid.
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
struct AggregationPlan {
|
||||
int nunsplit{0}; // number of fastest dimensions un-split
|
||||
int rowsize{0}; // ranks in the aggregation (row) communicator
|
||||
int rowrank{0}; // our logical (lexicographic) index within the row
|
||||
uint64_t lsites{0}; // sites per rank -- invariant under the permutation
|
||||
uint64_t chunk{0}; // sites in one globally contiguous run owned by the row
|
||||
std::unique_ptr<CartesianCommunicator> rowcomm;
|
||||
// counts and displacements are indexed by rank within rowcomm
|
||||
std::vector<int> sendcounts, senddispls, recvcounts, recvdispls;
|
||||
std::vector<uint64_t> scatter; // recv slot -> slot in the aggregated buffer
|
||||
std::vector<uint64_t> extentGsite; // global lex site index of extent start
|
||||
std::vector<uint64_t> extentLocal; // offset of extent within aggregated buffer
|
||||
std::vector<uint64_t> extentSites; // sites in this extent
|
||||
};
|
||||
|
||||
static inline void BuildAggregationPlan(GridBase *grid,uint64_t fobjSize,AggregationPlan &p)
|
||||
{
|
||||
int ndim = grid->Dimensions();
|
||||
Coordinate psizes = grid->ProcessorGrid();
|
||||
Coordinate pcoor = grid->ThisProcessorCoor();
|
||||
Coordinate gLattice= grid->GlobalDimensions();
|
||||
Coordinate lLattice= grid->LocalDimensions();
|
||||
Coordinate lstart = grid->LocalStarts();
|
||||
|
||||
uint64_t lsites = grid->lSites();
|
||||
p.lsites = lsites;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Un-splitting dims 0..k-1 gives the row a contiguous run of
|
||||
// chunk(k) = prod_{d<k} gLattice[d] * lLattice[k]
|
||||
// sites, and each rank writes extents of min(chunk,lsites). Take the
|
||||
// smallest k that reaches the target so we disturb as few dimensions --
|
||||
// and move as little data -- as possible.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
int k = ndim-1;
|
||||
for(int trial=1; trial<ndim; trial++){
|
||||
uint64_t chunk = lLattice[trial];
|
||||
for(int d=0; d<trial; d++) chunk *= gLattice[d];
|
||||
if ( std::min(chunk,lsites)*fobjSize >= aggregateTargetBytes ) { k = trial; break; }
|
||||
}
|
||||
p.nunsplit = k;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// The box the row collectively owns, expressed in global coordinates.
|
||||
// Restricting the global lexicographic order to this box preserves the
|
||||
// ordering, so the row index below is monotone in the global index.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
Coordinate B(ndim), S(ndim);
|
||||
for(int d=0; d<ndim; d++){
|
||||
if ( d<k ) { B[d] = gLattice[d]; S[d] = 0; }
|
||||
else { B[d] = lLattice[d]; S[d] = lstart[d]; }
|
||||
}
|
||||
|
||||
uint64_t chunk = lLattice[k];
|
||||
for(int d=0; d<k; d++) chunk *= gLattice[d];
|
||||
p.chunk = chunk;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Row communicator: the ranks sharing the process coordinates of the slow
|
||||
// (still split) dimensions. This is the sub-division the Cartesian
|
||||
// communicator already performs for AllToAll(dim,...), widened from one
|
||||
// dimension to the k fastest.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
Coordinate row(ndim,1);
|
||||
for(int d=0; d<k; d++) row[d] = psizes[d];
|
||||
int srank;
|
||||
p.rowcomm.reset(new CartesianCommunicator(row,*grid,srank));
|
||||
p.rowsize = p.rowcomm->ProcessorCount();
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Our logical index in the row is the forward lexicographic index of the
|
||||
// un-split process coordinates, so that increasing logical index means
|
||||
// increasing global lexicographic position in the file. The communicator
|
||||
// numbers its own ranks by the reversed (MPI) convention, so build the map
|
||||
// between the two rather than assuming either.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
int64_t logical=0, lstride=1;
|
||||
for(int d=0; d<k; d++){ logical += pcoor[d]*lstride; lstride *= psizes[d]; }
|
||||
GRID_ASSERT(lstride == (int64_t)p.rowsize);
|
||||
p.rowrank = (int)logical;
|
||||
|
||||
std::vector<uint64_t> commOf(p.rowsize,0);
|
||||
commOf[p.rowrank] = (uint64_t)p.rowcomm->ThisRank();
|
||||
p.rowcomm->GlobalSumVector(&commOf[0],p.rowsize);
|
||||
|
||||
uint64_t mystart = (uint64_t)p.rowrank * lsites;
|
||||
uint64_t myend = mystart + lsites;
|
||||
|
||||
Coordinate lcoor(ndim), bcoor(ndim), gcoor(ndim);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Send side. Walking our local sites in local lexicographic order walks
|
||||
// the row index monotonically, so the send buffer is iodata untouched and
|
||||
// we need only the per destination counts.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
std::vector<int> sendLogical(p.rowsize,0);
|
||||
for(uint64_t L=0; L<lsites; L++){
|
||||
Lexicographic::CoorFromIndex(lcoor,L,lLattice);
|
||||
for(int d=0; d<ndim; d++) bcoor[d] = (d<k) ? (lstart[d]+lcoor[d]) : lcoor[d];
|
||||
int64_t ri; Lexicographic::IndexFromCoor(bcoor,ri,B);
|
||||
sendLogical[ ri/(int64_t)lsites ]++;
|
||||
}
|
||||
p.sendcounts.assign(p.rowsize,0);
|
||||
p.senddispls.assign(p.rowsize,0);
|
||||
{ int64_t disp=0;
|
||||
for(int d=0; d<p.rowsize; d++){ // send buffer is in logical order
|
||||
int c = (int)commOf[d];
|
||||
p.sendcounts[c] = sendLogical[d];
|
||||
p.senddispls[c] = (int)disp;
|
||||
disp += sendLogical[d];
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Receive side. For each slot of our aggregated range work out which rank
|
||||
// of the row owns it. Within one source the slots arrive in increasing row
|
||||
// index order, which is the order the source sends them in.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
std::vector<int> recvLogical(p.rowsize,0), recvDisplLogical(p.rowsize,0);
|
||||
std::vector<int> source(lsites);
|
||||
for(uint64_t pos=0; pos<lsites; pos++){
|
||||
Lexicographic::CoorFromIndex(bcoor,(int64_t)(mystart+pos),B);
|
||||
int64_t j=0, jstride=1;
|
||||
for(int d=0; d<k; d++){ j += (bcoor[d]/lLattice[d])*jstride; jstride *= psizes[d]; }
|
||||
source[pos] = (int)j;
|
||||
recvLogical[j]++;
|
||||
}
|
||||
p.recvcounts.assign(p.rowsize,0);
|
||||
p.recvdispls.assign(p.rowsize,0);
|
||||
{ int64_t disp=0;
|
||||
for(int s=0; s<p.rowsize; s++){ // recv buffer is in logical order
|
||||
int c = (int)commOf[s];
|
||||
recvDisplLogical[s] = (int)disp;
|
||||
p.recvcounts[c] = recvLogical[s];
|
||||
p.recvdispls[c] = (int)disp;
|
||||
disp += recvLogical[s];
|
||||
}
|
||||
}
|
||||
p.scatter.resize(lsites);
|
||||
{
|
||||
std::vector<int> fill(p.rowsize,0);
|
||||
for(uint64_t pos=0; pos<lsites; pos++){
|
||||
int j = source[pos];
|
||||
p.scatter[ recvDisplLogical[j] + fill[j]++ ] = pos;
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// The two sides are derived independently; make them check each other.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
{
|
||||
std::vector<uint64_t> sendc(p.rowsize),recvc(p.rowsize);
|
||||
for(int c=0;c<p.rowsize;c++) sendc[c]=(uint64_t)p.sendcounts[c];
|
||||
p.rowcomm->AllToAll(&sendc[0],&recvc[0],1,sizeof(uint64_t));
|
||||
for(int c=0;c<p.rowsize;c++) GRID_ASSERT((int)recvc[c]==p.recvcounts[c]);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Decompose our range into globally contiguous file extents.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
for(uint64_t c = mystart/chunk; c <= (myend-1)/chunk; c++){
|
||||
uint64_t lo = std::max(mystart, c*chunk);
|
||||
uint64_t hi = std::min(myend, (c+1)*chunk);
|
||||
Lexicographic::CoorFromIndex(bcoor,(int64_t)(c*chunk),B);
|
||||
for(int d=0;d<ndim;d++) gcoor[d] = (d<k) ? bcoor[d] : bcoor[d]+S[d];
|
||||
int64_t gbase; Lexicographic::IndexFromCoor(gcoor,gbase,gLattice);
|
||||
p.extentGsite.push_back( (uint64_t)gbase + (lo - c*chunk) );
|
||||
p.extentLocal.push_back( lo - mystart );
|
||||
p.extentSites.push_back( hi - lo );
|
||||
}
|
||||
}
|
||||
|
||||
static inline void ReportAggregationPlan(GridBase *grid,const AggregationPlan &p,uint64_t fobjSize,const char *what)
|
||||
{
|
||||
if ( !grid->IsBoss() ) return;
|
||||
std::cout << GridLogMessage << "IOobject: aggregate " << what
|
||||
<< " un-splitting " << p.nunsplit << " fastest dimensions, row of "
|
||||
<< p.rowsize << " ranks" << std::endl;
|
||||
std::cout << GridLogMessage << "IOobject: aggregate " << p.extentSites.size()
|
||||
<< " extent(s)/rank, first " << p.extentSites[0]*fobjSize/1024./1024. << " MB"
|
||||
<< " (target " << aggregateTargetBytes/1024./1024. << " MB)" << std::endl;
|
||||
std::cout << GridLogMessage << "IOobject: aggregate buffer overhead "
|
||||
<< p.lsites*fobjSize/1024./1024. << " MB/rank" << std::endl;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// Stage timings. The interesting quantity is the slowest rank, since every
|
||||
// stage is followed sooner or later by a synchronisation, so reduce with
|
||||
// GlobalMax rather than reporting whatever the boss happened to see.
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
static inline void ReportStages(GridBase *grid,const char *what,
|
||||
const std::vector<const char *> &names,
|
||||
std::vector<RealD> &useconds)
|
||||
{
|
||||
GRID_ASSERT(names.size()==useconds.size());
|
||||
for(uint64_t i=0;i<useconds.size();i++) grid->GlobalMax(useconds[i]);
|
||||
if ( grid->IsBoss() ) {
|
||||
std::cout << GridLogMessage << "IOobject: aggregate " << what << " stages (max over ranks, s):";
|
||||
for(uint64_t i=0;i<names.size();i++)
|
||||
std::cout << " " << names[i] << " " << useconds[i]/1.0e6;
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
template<class fobj>
|
||||
static inline void AggregateExchange(GridBase *grid,AggregationPlan &p,std::vector<fobj> &iodata,
|
||||
std::vector<fobj> &aggregated,int forward)
|
||||
{
|
||||
uint64_t lsites = p.lsites;
|
||||
GridStopWatch talloc,tperm,tcomm;
|
||||
|
||||
talloc.Start();
|
||||
std::vector<fobj> tmp(lsites);
|
||||
talloc.Stop();
|
||||
|
||||
if ( forward ) { // iodata (local order) -> aggregated (lexicographic order)
|
||||
tcomm.Start();
|
||||
p.rowcomm->AllToAllV(&iodata[0],p.sendcounts,p.senddispls,
|
||||
&tmp[0], p.recvcounts,p.recvdispls,sizeof(fobj));
|
||||
tcomm.Stop();
|
||||
tperm.Start();
|
||||
thread_for(s,lsites,{ aggregated[p.scatter[s]] = tmp[s]; });
|
||||
tperm.Stop();
|
||||
} else { // aggregated -> iodata, the exact mirror
|
||||
tperm.Start();
|
||||
thread_for(s,lsites,{ tmp[s] = aggregated[p.scatter[s]]; });
|
||||
tperm.Stop();
|
||||
tcomm.Start();
|
||||
p.rowcomm->AllToAllV(&tmp[0], p.recvcounts,p.recvdispls,
|
||||
&iodata[0],p.sendcounts,p.senddispls,sizeof(fobj));
|
||||
tcomm.Stop();
|
||||
}
|
||||
|
||||
std::vector<RealD> us = { (RealD)talloc.useconds(), (RealD)tperm.useconds(), (RealD)tcomm.useconds() };
|
||||
ReportStages(grid,forward?"exchange (write)":"exchange (read)",
|
||||
{"alloc","permute","alltoallv"},us);
|
||||
}
|
||||
|
||||
template<class fobj>
|
||||
static inline void AggregateWrite(GridBase *grid,AggregationPlan &p,std::vector<fobj> &aggregated,
|
||||
std::string file,uint64_t offset)
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// All ranks write concurrently into a shared file, so the file must exist
|
||||
// before any of them open it for update, but it does NOT have to be the
|
||||
// right length first: the extents tile the record exactly, so writing them
|
||||
// extends a short file to precisely offset+payload.
|
||||
//
|
||||
// Records are created in sequence, so this payload ends the file: the
|
||||
// length must end up precisely offset+payload. Anything beyond is left
|
||||
// over from whatever the file previously held and must not survive -- a
|
||||
// shorter new record written over a longer old one would otherwise leave
|
||||
// a trailing fragment of the previous contents masquerading as data.
|
||||
// That is the only case needing a truncate, so stat first and truncate
|
||||
// afterwards only when the size actually came out wrong. Measured on
|
||||
// Frontier, an unconditional truncate up front cost 0.22 to 5.4 s per
|
||||
// record -- 15 to 25% of a 19 GB write and 100% of a small one -- while
|
||||
// create, open and close together cost a few milliseconds. It is per
|
||||
// record, so multi record files do not amortise it away.
|
||||
//
|
||||
// ::truncate is used because the C++ standard library cannot express this.
|
||||
// std::filebuf has no length operation at all; ios::trunc only truncates to
|
||||
// zero; seeking past the end and writing a byte can grow a file but never
|
||||
// shrink one; and there is no portable way to recover a descriptor from a
|
||||
// stream in order to call ftruncate. C++17 does finally offer
|
||||
// std::filesystem::resize_file, but that would be Grid's first <filesystem>
|
||||
// dependency and needs -lstdc++fs on the older toolchains still in use.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
GridStopWatch tcreate,ttrunc,tbar,topen,twrite,tclose,tskew;
|
||||
uint64_t need = offset + (uint64_t)grid->_gsites*sizeof(fobj);
|
||||
|
||||
tcreate.Start();
|
||||
if ( grid->IsBoss() ) {
|
||||
// opening for update needs the file to exist; create one only if not
|
||||
std::fstream probe(file,std::ios::binary|std::ios::out|std::ios::in);
|
||||
if ( !probe.is_open() ) {
|
||||
std::ofstream create(file,std::ios::binary|std::ios::out);
|
||||
create.close();
|
||||
}
|
||||
}
|
||||
tcreate.Stop();
|
||||
|
||||
tbar.Start();
|
||||
grid->Barrier();
|
||||
tbar.Stop();
|
||||
|
||||
std::ofstream fout;
|
||||
fout.exceptions( std::fstream::failbit | std::fstream::badbit );
|
||||
try {
|
||||
topen.Start();
|
||||
fout.open(file,std::ios::binary|std::ios::out|std::ios::in);
|
||||
topen.Stop();
|
||||
twrite.Start();
|
||||
for(uint64_t e=0;e<p.extentSites.size();e++){
|
||||
fout.seekp(offset + p.extentGsite[e]*sizeof(fobj));
|
||||
fout.write((char *)&aggregated[p.extentLocal[e]],p.extentSites[e]*sizeof(fobj));
|
||||
}
|
||||
twrite.Stop();
|
||||
tclose.Start();
|
||||
fout.close(); // flushes the stream buffer; does not force writeback
|
||||
tclose.Stop();
|
||||
} catch (const std::fstream::failure& exc) {
|
||||
std::cout << GridLogError << "Error in aggregate write to " << file << std::endl;
|
||||
std::cout << GridLogError << "Exception description: " << exc.what() << std::endl;
|
||||
GridAbort();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
// Timed apart from the truncate that follows it. seek+write above is the
|
||||
// slowest rank; this barrier is what the fastest rank then waits, so the
|
||||
// pair separates the write cost from the spread across ranks. Folding it
|
||||
// into the truncate makes a millisecond stat look like a second.
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
tskew.Start();
|
||||
grid->Barrier(); // every extent must be on its way first
|
||||
tskew.Stop();
|
||||
|
||||
ttrunc.Start();
|
||||
if ( grid->IsBoss() ) {
|
||||
struct stat sb;
|
||||
int ierr = ::stat(file.c_str(),&sb);
|
||||
GRID_ASSERT(ierr==0);
|
||||
if ( (uint64_t)sb.st_size != need ) { // only when a longer record preceded us
|
||||
ierr = ::truncate(file.c_str(),(off_t)need);
|
||||
GRID_ASSERT(ierr==0);
|
||||
}
|
||||
}
|
||||
grid->Barrier();
|
||||
ttrunc.Stop();
|
||||
|
||||
std::vector<RealD> us = { (RealD)tcreate.useconds(), (RealD)tbar.useconds(),
|
||||
(RealD)topen.useconds(), (RealD)twrite.useconds(),
|
||||
(RealD)tclose.useconds(), (RealD)tskew.useconds(),
|
||||
(RealD)ttrunc.useconds() };
|
||||
ReportStages(grid,"write",{"create","barrier","open","seek+write","close","skew","stat+truncate"},us);
|
||||
}
|
||||
|
||||
template<class fobj>
|
||||
static inline void AggregateRead(GridBase *grid,AggregationPlan &p,std::vector<fobj> &aggregated,
|
||||
std::string file,uint64_t offset)
|
||||
{
|
||||
GridStopWatch topen,tread,tclose;
|
||||
std::ifstream fin;
|
||||
topen.Start();
|
||||
fin.open(file,std::ios::binary|std::ios::in);
|
||||
topen.Stop();
|
||||
tread.Start();
|
||||
for(uint64_t e=0;e<p.extentSites.size();e++){
|
||||
fin.seekg(offset + p.extentGsite[e]*sizeof(fobj));
|
||||
fin.read((char *)&aggregated[p.extentLocal[e]],p.extentSites[e]*sizeof(fobj));
|
||||
GRID_ASSERT(fin.fail()==0);
|
||||
}
|
||||
tread.Stop();
|
||||
tclose.Start();
|
||||
fin.close();
|
||||
tclose.Stop();
|
||||
|
||||
std::vector<RealD> us = { (RealD)topen.useconds(), (RealD)tread.useconds(), (RealD)tclose.useconds() };
|
||||
ReportStages(grid,"read",{"open","seek+read","close"},us);
|
||||
}
|
||||
#endif
|
||||
|
||||
template<class word,class fobj>
|
||||
static inline void IOobject(word w,
|
||||
GridBase *grid,
|
||||
@@ -694,18 +302,6 @@ class BinaryIO {
|
||||
lStart[d] = 0;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// Aggregate the lexicographic layout onto contiguous per rank extents
|
||||
// ourselves rather than leaving it to MPI-IO collective buffering
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
int aggregate = (control & BINARYIO_AGGREGATE)
|
||||
&& (control & BINARYIO_LEXICOGRAPHIC)
|
||||
&& !(control & BINARYIO_MASTER_APPEND)
|
||||
&& (nrank > 1);
|
||||
#ifndef USE_MPI_IO
|
||||
GRID_ASSERT(aggregate==0); // BINARYIO_AGGREGATE requires MPI
|
||||
#endif
|
||||
|
||||
#ifdef USE_MPI_IO
|
||||
std::vector<int> distribs(ndim,MPI_DISTRIBUTE_BLOCK);
|
||||
std::vector<int> dargs (ndim,MPI_DISTRIBUTE_DFLT_DARG);
|
||||
@@ -733,8 +329,6 @@ class BinaryIO {
|
||||
ierr = MPI_Type_contiguous(numword,mpiword,&mpiObject); GRID_ASSERT(ierr==0);
|
||||
ierr = MPI_Type_commit(&mpiObject);
|
||||
|
||||
// The subarray view is what aggregation exists to avoid; do not build it
|
||||
if ( !aggregate ) {
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// File global array data type
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
@@ -746,7 +340,6 @@ class BinaryIO {
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
ierr=MPI_Type_create_subarray(ndim,&lLattice[0],&lLattice[0],&lStart[0],MPI_ORDER_FORTRAN, mpiObject,&localArray); GRID_ASSERT(ierr==0);
|
||||
ierr=MPI_Type_commit(&localArray); GRID_ASSERT(ierr==0);
|
||||
}
|
||||
#endif
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
@@ -765,19 +358,7 @@ class BinaryIO {
|
||||
|
||||
timer.Start();
|
||||
|
||||
if ( aggregate ) {
|
||||
#ifdef USE_MPI_IO
|
||||
std::cout<< GridLogMessage<<"IOobject: aggregate read I/O "<< file<< std::endl;
|
||||
AggregationPlan plan;
|
||||
BuildAggregationPlan(grid,sizeof(fobj),plan);
|
||||
ReportAggregationPlan(grid,plan,sizeof(fobj),"read");
|
||||
std::vector<fobj> aggregated(lsites);
|
||||
AggregateRead(grid,plan,aggregated,file,offset);
|
||||
AggregateExchange(grid,plan,iodata,aggregated,0);
|
||||
#else
|
||||
GRID_ASSERT(0);
|
||||
#endif
|
||||
} else if ( (control & BINARYIO_LEXICOGRAPHIC) && (nrank > 1) ) {
|
||||
if ( (control & BINARYIO_LEXICOGRAPHIC) && (nrank > 1) ) {
|
||||
#ifdef USE_MPI_IO
|
||||
std::cout<< GridLogMessage<<"IOobject: MPI read I/O "<< file<< std::endl;
|
||||
ierr=MPI_File_open(grid->communicator,(char *) file.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &fh); GRID_ASSERT(ierr==0);
|
||||
@@ -835,25 +416,7 @@ class BinaryIO {
|
||||
grid->Barrier();
|
||||
|
||||
timer.Start();
|
||||
if ( aggregate ) {
|
||||
#ifdef USE_MPI_IO
|
||||
std::cout << GridLogMessage <<"IOobject: aggregate write I/O " << file << std::endl;
|
||||
AggregationPlan plan;
|
||||
BuildAggregationPlan(grid,sizeof(fobj),plan);
|
||||
ReportAggregationPlan(grid,plan,sizeof(fobj),"write");
|
||||
std::vector<fobj> aggregated(lsites);
|
||||
AggregateExchange(grid,plan,iodata,aggregated,1);
|
||||
AggregateWrite(grid,plan,aggregated,file,offset);
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
// Not every rank ends at the end of the payload, so the position can
|
||||
// not be recovered from a file handle. Callers (Lime record chaining)
|
||||
// rely on this being the first byte past the record.
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
offset = offset + (uint64_t)grid->_gsites*sizeof(fobj);
|
||||
#else
|
||||
GRID_ASSERT(0);
|
||||
#endif
|
||||
} else if ( (control & BINARYIO_LEXICOGRAPHIC) && (nrank > 1) ) {
|
||||
if ( (control & BINARYIO_LEXICOGRAPHIC) && (nrank > 1) ) {
|
||||
#ifdef USE_MPI_IO
|
||||
std::cout << GridLogMessage <<"IOobject: MPI write I/O " << file << std::endl;
|
||||
ierr = MPI_File_open(grid->communicator, (char *)file.c_str(), MPI_MODE_RDWR | MPI_MODE_CREATE, MPI_INFO_NULL, &fh);
|
||||
@@ -898,26 +461,12 @@ class BinaryIO {
|
||||
|
||||
std::ofstream fout;
|
||||
fout.exceptions ( std::fstream::failbit | std::fstream::badbit );
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// Grid's model is that the boss rank performs the metadata
|
||||
// operations and every other rank only seeks and writes into a file
|
||||
// that already exists. Opening with ios::out on all ranks broke that:
|
||||
// it is O_TRUNC, so a rank opening late truncated the file back to
|
||||
// zero after an earlier rank had written its segment, leaving a hole
|
||||
// in its place. The barriers around this block are outside it and do
|
||||
// not order the opens against the writes. Let the boss create and
|
||||
// empty the file, then everyone opens for update only. Same resulting
|
||||
// length, one metadata operation instead of one per rank, no race.
|
||||
////////////////////////////////////////////////////////////////////
|
||||
if ( !offset && grid->IsBoss() ) { // offset zero: this record starts the file
|
||||
std::ofstream create(file,std::ios::binary|std::ios::out);
|
||||
create.close();
|
||||
}
|
||||
grid->Barrier();
|
||||
|
||||
try {
|
||||
fout.open(file,std::ios::binary|std::ios::out|std::ios::in);
|
||||
if (offset) { // Must already exist and contain data
|
||||
fout.open(file,std::ios::binary|std::ios::out|std::ios::in);
|
||||
} else { // Allow create
|
||||
fout.open(file,std::ios::binary|std::ios::out);
|
||||
}
|
||||
} catch (const std::fstream::failure& exc) {
|
||||
std::cout << GridLogError << "Error in opening the file " << file << " for output" <<std::endl;
|
||||
std::cout << GridLogError << "Exception description: " << exc.what() << std::endl;
|
||||
@@ -928,7 +477,7 @@ class BinaryIO {
|
||||
exit(1);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
if ( control & BINARYIO_MASTER_APPEND ) {
|
||||
try {
|
||||
fout.seekp(0,fout.end);
|
||||
@@ -999,7 +548,7 @@ class BinaryIO {
|
||||
uint32_t &nersc_csum,
|
||||
uint32_t &scidac_csuma,
|
||||
uint32_t &scidac_csumb,
|
||||
int control=DefaultControl()
|
||||
int control=BINARYIO_LEXICOGRAPHIC
|
||||
)
|
||||
{
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
@@ -1038,7 +587,7 @@ class BinaryIO {
|
||||
uint32_t &nersc_csum,
|
||||
uint32_t &scidac_csuma,
|
||||
uint32_t &scidac_csumb,
|
||||
int control=DefaultControl())
|
||||
int control=BINARYIO_LEXICOGRAPHIC)
|
||||
{
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
typedef typename vobj::Realified::scalar_type word; word w=0;
|
||||
@@ -1125,7 +674,7 @@ class BinaryIO {
|
||||
std::cout << GridLogMessage << "RNG read I/O on file " << file << std::endl;
|
||||
|
||||
std::vector<RNGstate> iodata(lsites);
|
||||
IOobject(w,grid,iodata,file,offset,format,BINARYIO_READ|DefaultControl(),
|
||||
IOobject(w,grid,iodata,file,offset,format,BINARYIO_READ|BINARYIO_LEXICOGRAPHIC,
|
||||
nersc_csum,scidac_csuma,scidac_csumb);
|
||||
|
||||
timer.Start();
|
||||
@@ -1204,7 +753,7 @@ class BinaryIO {
|
||||
});
|
||||
timer.Stop();
|
||||
|
||||
IOobject(w,grid,iodata,file,offset,format,BINARYIO_WRITE|DefaultControl(),
|
||||
IOobject(w,grid,iodata,file,offset,format,BINARYIO_WRITE|BINARYIO_LEXICOGRAPHIC,
|
||||
nersc_csum,scidac_csuma,scidac_csumb);
|
||||
iodata.resize(1);
|
||||
{
|
||||
|
||||
@@ -212,7 +212,7 @@ class GridLimeReader : public BinaryIO {
|
||||
// Read a generic lattice field and verify checksum
|
||||
////////////////////////////////////////////
|
||||
template<class vobj>
|
||||
void readLimeLatticeBinaryObject(Lattice<vobj> &field,std::string record_name,int control=BINARYIO_LEXICOGRAPHIC|BINARYIO_AGGREGATE)
|
||||
void readLimeLatticeBinaryObject(Lattice<vobj> &field,std::string record_name,int control=BINARYIO_LEXICOGRAPHIC)
|
||||
{
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
scidacChecksum scidacChecksum_;
|
||||
@@ -260,7 +260,8 @@ class GridLimeReader : public BinaryIO {
|
||||
<< " / field= " << n2ck << " / rdiff= " << GRID_FIELD_NORM_CALC(FieldNormMetaData_,n2ck) << std::endl;
|
||||
GRID_FIELD_NORM_CHECK(FieldNormMetaData_,n2ck);
|
||||
}
|
||||
assert(scidacChecksumVerify(scidacChecksum_,scidac_csuma,scidac_csumb)==1);
|
||||
// assert(scidacChecksumVerify(scidacChecksum_,scidac_csuma,scidac_csumb)==1);
|
||||
scidacChecksumVerify(scidacChecksum_,scidac_csuma,scidac_csumb);
|
||||
|
||||
// find out if next field is a GridFieldNorm
|
||||
return;
|
||||
@@ -414,7 +415,7 @@ class GridLimeWriter : public BinaryIO
|
||||
// in communicator used by the field.Grid()
|
||||
////////////////////////////////////////////////////
|
||||
template<class vobj>
|
||||
void writeLimeLatticeBinaryObject(Lattice<vobj> &field,std::string record_name,int control=BINARYIO_LEXICOGRAPHIC|BINARYIO_AGGREGATE)
|
||||
void writeLimeLatticeBinaryObject(Lattice<vobj> &field,std::string record_name,int control=BINARYIO_LEXICOGRAPHIC)
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// NB: FILE and iostream are jointly writing disjoint sequences in the
|
||||
@@ -519,7 +520,7 @@ class ScidacWriter : public GridLimeWriter {
|
||||
template <class vobj, class userRecord>
|
||||
void writeScidacFieldRecord(Lattice<vobj> &field,userRecord _userRecord,
|
||||
const unsigned int recordScientificPrec = 0,
|
||||
int control=BINARYIO_LEXICOGRAPHIC|BINARYIO_AGGREGATE)
|
||||
int control=BINARYIO_LEXICOGRAPHIC)
|
||||
{
|
||||
GridBase * grid = field.Grid();
|
||||
|
||||
@@ -561,7 +562,7 @@ class ScidacReader : public GridLimeReader {
|
||||
////////////////////////////////////////////////
|
||||
template <class vobj, class userRecord>
|
||||
void readScidacFieldRecord(Lattice<vobj> &field,userRecord &_userRecord,
|
||||
int control=BINARYIO_LEXICOGRAPHIC|BINARYIO_AGGREGATE)
|
||||
int control=BINARYIO_LEXICOGRAPHIC)
|
||||
{
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
GridBase * grid = field.Grid();
|
||||
|
||||
@@ -180,7 +180,7 @@ template<class Impl>
|
||||
class GaugeStatistics
|
||||
{
|
||||
public:
|
||||
void operator()(typename Impl::Field & data,FieldMetaData &header)
|
||||
void operator()(Lattice<vLorentzColourMatrixD> & data,FieldMetaData &header)
|
||||
{
|
||||
header.link_trace = WilsonLoops<Impl>::linkTrace(data);
|
||||
header.plaquette = WilsonLoops<Impl>::avgPlaquette(data);
|
||||
@@ -188,24 +188,13 @@ public:
|
||||
};
|
||||
typedef GaugeStatistics<PeriodicGimplD> PeriodicGaugeStatistics;
|
||||
typedef GaugeStatistics<ConjugateGimplD> ConjugateGaugeStatistics;
|
||||
typedef GaugeStatistics<lexPeriodicGimplD> lexPeriodicGaugeStatistics;
|
||||
typedef GaugeStatistics<lexConjugateGimplD> lexConjugateGaugeStatistics;
|
||||
template<> inline void PrepareMetaData<vLorentzColourMatrixD>(Lattice<vLorentzColourMatrixD> & field, FieldMetaData &header)
|
||||
{
|
||||
GridBase *grid = field.Grid();
|
||||
std::string format = getFormatString<vLorentzColourMatrixD>();
|
||||
header.floating_point = format;
|
||||
header.checksum = 0x0; // Nersc checksum unused in ILDG, Scidac
|
||||
GridMetaData(grid,header);
|
||||
MachineCharacteristics(header);
|
||||
}
|
||||
template<> inline void PrepareMetaData<sLorentzColourMatrixD>(Lattice<sLorentzColourMatrixD> & field, FieldMetaData &header)
|
||||
{
|
||||
GridBase *grid = field.Grid();
|
||||
std::string format = getFormatString<sLorentzColourMatrixD>();
|
||||
header.floating_point = format;
|
||||
header.checksum = 0x0; // Nersc checksum unused in ILDG, Scidac
|
||||
GridMetaData(grid,header);
|
||||
GridMetaData(grid,header);
|
||||
MachineCharacteristics(header);
|
||||
}
|
||||
|
||||
|
||||
+23
-80
@@ -122,7 +122,7 @@ public:
|
||||
field.checksum = std::stoul(header["CHECKSUM"],0,16);
|
||||
field.ensemble_id = header["ENSEMBLE_ID"];
|
||||
field.ensemble_label = header["ENSEMBLE_LABEL"];
|
||||
field.sequence_number = std::stol(header["SEQUENCE_NUMBER"]);
|
||||
// field.sequence_number = std::stol(header["SEQUENCE_NUMBER"]);
|
||||
field.creator = header["CREATOR"];
|
||||
field.creator_hardware = header["CREATOR_HARDWARE"];
|
||||
field.creation_date = header["CREATION_DATE"];
|
||||
@@ -136,14 +136,12 @@ public:
|
||||
// Now the meat: the object readers
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
template<class GaugeFieldType,class GaugeStats>
|
||||
static inline void readConfigurationInternal(GaugeFieldType &Umu,
|
||||
FieldMetaData& header,
|
||||
std::string file,
|
||||
GaugeStats GaugeStatisticsCalculator)
|
||||
template<class GaugeStats=PeriodicGaugeStatistics>
|
||||
static inline void readConfiguration(GaugeField &Umu,
|
||||
FieldMetaData& header,
|
||||
std::string file,
|
||||
GaugeStats GaugeStatisticsCalculator=GaugeStats())
|
||||
{
|
||||
typedef typename GaugeFieldType::vector_object vobj;
|
||||
typedef typename GaugeFieldType::scalar_object sobj;
|
||||
|
||||
GridBase *grid = Umu.Grid();
|
||||
uint64_t offset = readHeader(file,Umu.Grid(),header);
|
||||
@@ -164,24 +162,24 @@ public:
|
||||
const std::string stNC = std::to_string( Nc ) ;
|
||||
if ( header.data_type == std::string("4D_SU"+stNC+"_GAUGE") ) {
|
||||
if ( ieee32 || ieee32big ) {
|
||||
BinaryIO::readLatticeObject<vobj, LorentzColour2x3F>
|
||||
(Umu,file,Gauge3x2munger<LorentzColour2x3F,sobj>(), offset,format,
|
||||
BinaryIO::readLatticeObject<vLorentzColourMatrixD, LorentzColour2x3F>
|
||||
(Umu,file,Gauge3x2munger<LorentzColour2x3F,LorentzColourMatrix>(), offset,format,
|
||||
nersc_csum,scidac_csuma,scidac_csumb);
|
||||
}
|
||||
if ( ieee64 || ieee64big ) {
|
||||
BinaryIO::readLatticeObject<vobj, LorentzColour2x3D>
|
||||
(Umu,file,Gauge3x2munger<LorentzColour2x3D,sobj>(),offset,format,
|
||||
BinaryIO::readLatticeObject<vLorentzColourMatrixD, LorentzColour2x3D>
|
||||
(Umu,file,Gauge3x2munger<LorentzColour2x3D,LorentzColourMatrix>(),offset,format,
|
||||
nersc_csum,scidac_csuma,scidac_csumb);
|
||||
}
|
||||
} else if ( header.data_type == std::string("4D_SU"+stNC+"_GAUGE_"+stNC+"x"+stNC) ) {
|
||||
if ( ieee32 || ieee32big ) {
|
||||
BinaryIO::readLatticeObject<vobj,LorentzColourMatrixF>
|
||||
(Umu,file,GaugeSimpleMunger<LorentzColourMatrixF,sobj>(),offset,format,
|
||||
BinaryIO::readLatticeObject<vLorentzColourMatrixD,LorentzColourMatrixF>
|
||||
(Umu,file,GaugeSimpleMunger<LorentzColourMatrixF,LorentzColourMatrix>(),offset,format,
|
||||
nersc_csum,scidac_csuma,scidac_csumb);
|
||||
}
|
||||
if ( ieee64 || ieee64big ) {
|
||||
BinaryIO::readLatticeObject<vobj,LorentzColourMatrixD>
|
||||
(Umu,file,GaugeSimpleMunger<LorentzColourMatrixD,sobj>(),offset,format,
|
||||
BinaryIO::readLatticeObject<vLorentzColourMatrixD,LorentzColourMatrixD>
|
||||
(Umu,file,GaugeSimpleMunger<LorentzColourMatrixD,LorentzColourMatrix>(),offset,format,
|
||||
nersc_csum,scidac_csuma,scidac_csumb);
|
||||
}
|
||||
} else {
|
||||
@@ -200,11 +198,12 @@ public:
|
||||
if ( fabs(clone.plaquette -header.plaquette ) >= 1.0e-5 ) {
|
||||
std::cout << " Plaquette mismatch "<<std::endl;
|
||||
}
|
||||
if ( nersc_csum != header.checksum ) {
|
||||
if ( nersc_csum != header.checksum ) {
|
||||
std::cerr << " checksum mismatch " << std::endl;
|
||||
std::cerr << " plaqs " << clone.plaquette << " " << header.plaquette << std::endl;
|
||||
std::cerr << " trace " << clone.link_trace<< " " << header.link_trace<< std::endl;
|
||||
std::cerr << " nersc_csum " <<std::hex<< nersc_csum << " " << header.checksum<< std::dec<< std::endl;
|
||||
exit(0);
|
||||
}
|
||||
if(exitOnReadPlaquetteMismatch()) GRID_ASSERT(fabs(clone.plaquette -header.plaquette ) < 1.0e-5 );
|
||||
GRID_ASSERT(fabs(clone.link_trace-header.link_trace) < 1.0e-6 );
|
||||
@@ -213,26 +212,6 @@ public:
|
||||
std::cout<<GridLogMessage <<"NERSC Configuration "<<file<< " and plaquette, link trace, and checksum agree"<<std::endl;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Constrained frontends: vectorised and lexicographic gauge fields
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
template<class GaugeStats=PeriodicGaugeStatistics>
|
||||
static inline void readConfiguration(Lattice<vLorentzColourMatrixD> &Umu,
|
||||
FieldMetaData& header,
|
||||
std::string file,
|
||||
GaugeStats GaugeStatisticsCalculator=GaugeStats())
|
||||
{
|
||||
readConfigurationInternal(Umu,header,file,GaugeStatisticsCalculator);
|
||||
}
|
||||
template<class GaugeStats=lexPeriodicGaugeStatistics>
|
||||
static inline void readConfiguration(Lattice<sLorentzColourMatrixD> &Umu,
|
||||
FieldMetaData& header,
|
||||
std::string file,
|
||||
GaugeStats GaugeStatisticsCalculator=GaugeStats())
|
||||
{
|
||||
readConfigurationInternal(Umu,header,file,GaugeStatisticsCalculator);
|
||||
}
|
||||
|
||||
// Preferred interface
|
||||
template<class GaugeStats=PeriodicGaugeStatistics>
|
||||
static inline void writeConfiguration(Lattice<vLorentzColourMatrixD > &Umu,
|
||||
@@ -241,16 +220,7 @@ public:
|
||||
std::string ens_id = std::string("UKQCD"),
|
||||
unsigned int sequence_number = 1)
|
||||
{
|
||||
writeConfigurationInternal<Lattice<vLorentzColourMatrixD>,GaugeStats>(Umu,file,0,1,ens_label,ens_id,sequence_number);
|
||||
}
|
||||
template<class GaugeStats=lexPeriodicGaugeStatistics>
|
||||
static inline void writeConfiguration(Lattice<sLorentzColourMatrixD > &Umu,
|
||||
std::string file,
|
||||
std::string ens_label = std::string("DWF"),
|
||||
std::string ens_id = std::string("UKQCD"),
|
||||
unsigned int sequence_number = 1)
|
||||
{
|
||||
writeConfigurationInternal<Lattice<sLorentzColourMatrixD>,GaugeStats>(Umu,file,0,1,ens_label,ens_id,sequence_number);
|
||||
writeConfiguration(Umu,file,0,1,ens_label,ens_id,sequence_number);
|
||||
}
|
||||
template<class GaugeStats=PeriodicGaugeStatistics>
|
||||
static inline void writeConfiguration(Lattice<vLorentzColourMatrixD > &Umu,
|
||||
@@ -261,29 +231,7 @@ public:
|
||||
std::string ens_id = std::string("UKQCD"),
|
||||
unsigned int sequence_number = 1)
|
||||
{
|
||||
writeConfigurationInternal<Lattice<vLorentzColourMatrixD>,GaugeStats>(Umu,file,two_row,bits32,ens_label,ens_id,sequence_number);
|
||||
}
|
||||
template<class GaugeStats=lexPeriodicGaugeStatistics>
|
||||
static inline void writeConfiguration(Lattice<sLorentzColourMatrixD > &Umu,
|
||||
std::string file,
|
||||
int two_row,
|
||||
int bits32,
|
||||
std::string ens_label = std::string("DWF"),
|
||||
std::string ens_id = std::string("UKQCD"),
|
||||
unsigned int sequence_number = 1)
|
||||
{
|
||||
writeConfigurationInternal<Lattice<sLorentzColourMatrixD>,GaugeStats>(Umu,file,two_row,bits32,ens_label,ens_id,sequence_number);
|
||||
}
|
||||
template<class GaugeFieldType,class GaugeStats>
|
||||
static inline void writeConfigurationInternal(GaugeFieldType &Umu,
|
||||
std::string file,
|
||||
int two_row,
|
||||
int bits32,
|
||||
std::string ens_label = std::string("DWF"),
|
||||
std::string ens_id = std::string("UKQCD"),
|
||||
unsigned int sequence_number = 1)
|
||||
{
|
||||
typedef typename GaugeFieldType::vector_object vobj;
|
||||
typedef vLorentzColourMatrixD vobj;
|
||||
typedef typename vobj::scalar_object sobj;
|
||||
|
||||
FieldMetaData header;
|
||||
@@ -329,12 +277,9 @@ public:
|
||||
nersc_csum,scidac_csuma,scidac_csumb);
|
||||
}
|
||||
header.checksum = nersc_csum;
|
||||
if ( grid->IsBoss() ) {
|
||||
if ( grid->IsBoss() ) {
|
||||
writeHeader(header,file);
|
||||
}
|
||||
// The header is written twice; the checksum is only known after the data.
|
||||
// Other ranks must not proceed to read it until the rewrite has landed.
|
||||
grid->Barrier();
|
||||
|
||||
std::cout<<GridLogMessage <<"Written NERSC Configuration on "<< file << " checksum "
|
||||
<<std::hex<<header.checksum
|
||||
@@ -385,14 +330,11 @@ public:
|
||||
uint32_t nersc_csum,scidac_csuma,scidac_csumb;
|
||||
BinaryIO::writeRNG(serial,parallel,file,offset,nersc_csum,scidac_csuma,scidac_csumb);
|
||||
header.checksum = nersc_csum;
|
||||
if ( grid->IsBoss() ) {
|
||||
if ( grid->IsBoss() ) {
|
||||
offset = writeHeader(header,file);
|
||||
}
|
||||
// As for the gauge field: the checksum is only known after the data, so
|
||||
// the header is rewritten. Hold the other ranks until that has landed.
|
||||
grid->Barrier();
|
||||
|
||||
std::cout<<GridLogMessage
|
||||
std::cout<<GridLogMessage
|
||||
<<"Written NERSC RNG STATE "<<file<< " checksum "
|
||||
<<std::hex<<header.checksum
|
||||
<<std::dec<<std::endl;
|
||||
@@ -430,8 +372,9 @@ public:
|
||||
uint32_t nersc_csum,scidac_csuma,scidac_csumb;
|
||||
BinaryIO::readRNG(serial,parallel,file,offset,nersc_csum,scidac_csuma,scidac_csumb);
|
||||
|
||||
if ( nersc_csum != header.checksum ) {
|
||||
if ( nersc_csum != header.checksum ) {
|
||||
std::cerr << "checksum mismatch "<<std::hex<< nersc_csum <<" "<<header.checksum<<std::dec<<std::endl;
|
||||
exit(0);
|
||||
}
|
||||
GRID_ASSERT(nersc_csum == header.checksum );
|
||||
|
||||
|
||||
@@ -93,7 +93,8 @@ inline uint64_t cyclecount(void){
|
||||
}
|
||||
#elif defined __x86_64__
|
||||
inline uint64_t cyclecount(void){
|
||||
return (uint64_t)0;
|
||||
uint64_t ret = __rdtsc();
|
||||
return (uint64_t)ret;
|
||||
}
|
||||
#else
|
||||
|
||||
|
||||
+43
-92
@@ -127,6 +127,7 @@ typedef iSpinMatrix<ComplexD > SpinMatrixD;
|
||||
typedef iSpinMatrix<vComplex > vSpinMatrix;
|
||||
typedef iSpinMatrix<vComplexF> vSpinMatrixF;
|
||||
typedef iSpinMatrix<vComplexD> vSpinMatrixD;
|
||||
typedef iSpinMatrix<vComplexD2> vSpinMatrixD2;
|
||||
|
||||
// Colour Matrix
|
||||
typedef iColourMatrix<Complex > ColourMatrix;
|
||||
@@ -136,6 +137,7 @@ typedef iColourMatrix<ComplexD > ColourMatrixD;
|
||||
typedef iColourMatrix<vComplex > vColourMatrix;
|
||||
typedef iColourMatrix<vComplexF> vColourMatrixF;
|
||||
typedef iColourMatrix<vComplexD> vColourMatrixD;
|
||||
typedef iColourMatrix<vComplexD2> vColourMatrixD2;
|
||||
|
||||
// SpinColour matrix
|
||||
typedef iSpinColourMatrix<Complex > SpinColourMatrix;
|
||||
@@ -145,6 +147,7 @@ typedef iSpinColourMatrix<ComplexD > SpinColourMatrixD;
|
||||
typedef iSpinColourMatrix<vComplex > vSpinColourMatrix;
|
||||
typedef iSpinColourMatrix<vComplexF> vSpinColourMatrixF;
|
||||
typedef iSpinColourMatrix<vComplexD> vSpinColourMatrixD;
|
||||
typedef iSpinColourMatrix<vComplexD2> vSpinColourMatrixD2;
|
||||
|
||||
// SpinColourSpinColour matrix
|
||||
typedef iSpinColourSpinColourMatrix<Complex > SpinColourSpinColourMatrix;
|
||||
@@ -154,6 +157,17 @@ typedef iSpinColourSpinColourMatrix<ComplexD > SpinColourSpinColourMatrixD;
|
||||
typedef iSpinColourSpinColourMatrix<vComplex > vSpinColourSpinColourMatrix;
|
||||
typedef iSpinColourSpinColourMatrix<vComplexF> vSpinColourSpinColourMatrixF;
|
||||
typedef iSpinColourSpinColourMatrix<vComplexD> vSpinColourSpinColourMatrixD;
|
||||
typedef iSpinColourSpinColourMatrix<vComplexD2> vSpinColourSpinColourMatrixD2;
|
||||
|
||||
// SpinColourSpinColour matrix
|
||||
typedef iSpinColourSpinColourMatrix<Complex > SpinColourSpinColourMatrix;
|
||||
typedef iSpinColourSpinColourMatrix<ComplexF > SpinColourSpinColourMatrixF;
|
||||
typedef iSpinColourSpinColourMatrix<ComplexD > SpinColourSpinColourMatrixD;
|
||||
|
||||
typedef iSpinColourSpinColourMatrix<vComplex > vSpinColourSpinColourMatrix;
|
||||
typedef iSpinColourSpinColourMatrix<vComplexF> vSpinColourSpinColourMatrixF;
|
||||
typedef iSpinColourSpinColourMatrix<vComplexD> vSpinColourSpinColourMatrixD;
|
||||
typedef iSpinColourSpinColourMatrix<vComplexD2> vSpinColourSpinColourMatrixD2;
|
||||
|
||||
// LorentzColour
|
||||
typedef iLorentzColourMatrix<Complex > LorentzColourMatrix;
|
||||
@@ -163,6 +177,7 @@ typedef iLorentzColourMatrix<ComplexD > LorentzColourMatrixD;
|
||||
typedef iLorentzColourMatrix<vComplex > vLorentzColourMatrix;
|
||||
typedef iLorentzColourMatrix<vComplexF> vLorentzColourMatrixF;
|
||||
typedef iLorentzColourMatrix<vComplexD> vLorentzColourMatrixD;
|
||||
typedef iLorentzColourMatrix<vComplexD2> vLorentzColourMatrixD2;
|
||||
|
||||
// LorentzComplex
|
||||
typedef iLorentzComplex<Complex > LorentzComplex;
|
||||
@@ -181,6 +196,7 @@ typedef iDoubleStoredColourMatrix<ComplexD > DoubleStoredColourMatrixD;
|
||||
typedef iDoubleStoredColourMatrix<vComplex > vDoubleStoredColourMatrix;
|
||||
typedef iDoubleStoredColourMatrix<vComplexF> vDoubleStoredColourMatrixF;
|
||||
typedef iDoubleStoredColourMatrix<vComplexD> vDoubleStoredColourMatrixD;
|
||||
typedef iDoubleStoredColourMatrix<vComplexD2> vDoubleStoredColourMatrixD2;
|
||||
|
||||
//G-parity flavour matrix
|
||||
typedef iGparityFlavourMatrix<Complex> GparityFlavourMatrix;
|
||||
@@ -190,6 +206,7 @@ typedef iGparityFlavourMatrix<ComplexD> GparityFlavourMatrixD;
|
||||
typedef iGparityFlavourMatrix<vComplex> vGparityFlavourMatrix;
|
||||
typedef iGparityFlavourMatrix<vComplexF> vGparityFlavourMatrixF;
|
||||
typedef iGparityFlavourMatrix<vComplexD> vGparityFlavourMatrixD;
|
||||
typedef iGparityFlavourMatrix<vComplexD2> vGparityFlavourMatrixD2;
|
||||
|
||||
|
||||
// Spin vector
|
||||
@@ -200,6 +217,7 @@ typedef iSpinVector<ComplexD> SpinVectorD;
|
||||
typedef iSpinVector<vComplex > vSpinVector;
|
||||
typedef iSpinVector<vComplexF> vSpinVectorF;
|
||||
typedef iSpinVector<vComplexD> vSpinVectorD;
|
||||
typedef iSpinVector<vComplexD2> vSpinVectorD2;
|
||||
|
||||
// Colour vector
|
||||
typedef iColourVector<Complex > ColourVector;
|
||||
@@ -209,6 +227,7 @@ typedef iColourVector<ComplexD> ColourVectorD;
|
||||
typedef iColourVector<vComplex > vColourVector;
|
||||
typedef iColourVector<vComplexF> vColourVectorF;
|
||||
typedef iColourVector<vComplexD> vColourVectorD;
|
||||
typedef iColourVector<vComplexD2> vColourVectorD2;
|
||||
|
||||
// SpinColourVector
|
||||
typedef iSpinColourVector<Complex > SpinColourVector;
|
||||
@@ -218,6 +237,7 @@ typedef iSpinColourVector<ComplexD> SpinColourVectorD;
|
||||
typedef iSpinColourVector<vComplex > vSpinColourVector;
|
||||
typedef iSpinColourVector<vComplexF> vSpinColourVectorF;
|
||||
typedef iSpinColourVector<vComplexD> vSpinColourVectorD;
|
||||
typedef iSpinColourVector<vComplexD2> vSpinColourVectorD2;
|
||||
|
||||
// HalfSpin vector
|
||||
typedef iHalfSpinVector<Complex > HalfSpinVector;
|
||||
@@ -227,6 +247,7 @@ typedef iHalfSpinVector<ComplexD> HalfSpinVectorD;
|
||||
typedef iHalfSpinVector<vComplex > vHalfSpinVector;
|
||||
typedef iHalfSpinVector<vComplexF> vHalfSpinVectorF;
|
||||
typedef iHalfSpinVector<vComplexD> vHalfSpinVectorD;
|
||||
typedef iHalfSpinVector<vComplexD2> vHalfSpinVectorD2;
|
||||
|
||||
// HalfSpinColour vector
|
||||
typedef iHalfSpinColourVector<Complex > HalfSpinColourVector;
|
||||
@@ -236,6 +257,7 @@ typedef iHalfSpinColourVector<ComplexD> HalfSpinColourVectorD;
|
||||
typedef iHalfSpinColourVector<vComplex > vHalfSpinColourVector;
|
||||
typedef iHalfSpinColourVector<vComplexF> vHalfSpinColourVectorF;
|
||||
typedef iHalfSpinColourVector<vComplexD> vHalfSpinColourVectorD;
|
||||
typedef iHalfSpinColourVector<vComplexD2> vHalfSpinColourVectorD2;
|
||||
|
||||
//G-parity flavour vector
|
||||
typedef iGparityFlavourVector<Complex > GparityFlavourVector;
|
||||
@@ -245,6 +267,7 @@ typedef iGparityFlavourVector<ComplexD> GparityFlavourVectorD;
|
||||
typedef iGparityFlavourVector<vComplex > vGparityFlavourVector;
|
||||
typedef iGparityFlavourVector<vComplexF> vGparityFlavourVectorF;
|
||||
typedef iGparityFlavourVector<vComplexD> vGparityFlavourVectorD;
|
||||
typedef iGparityFlavourVector<vComplexD2> vGparityFlavourVectorD2;
|
||||
|
||||
// singlets
|
||||
typedef iSinglet<Complex > TComplex; // FIXME This is painful. Tensor singlet complex type.
|
||||
@@ -254,6 +277,7 @@ typedef iSinglet<ComplexD> TComplexD; // FIXME This is painful. Tenso
|
||||
typedef iSinglet<vComplex > vTComplex ; // what if we don't know the tensor structure
|
||||
typedef iSinglet<vComplexF> vTComplexF; // what if we don't know the tensor structure
|
||||
typedef iSinglet<vComplexD> vTComplexD; // what if we don't know the tensor structure
|
||||
typedef iSinglet<vComplexD2> vTComplexD2; // what if we don't know the tensor structure
|
||||
|
||||
typedef iSinglet<Real > TReal; // Shouldn't need these; can I make it work without?
|
||||
typedef iSinglet<RealF> TRealF; // Shouldn't need these; can I make it work without?
|
||||
@@ -271,22 +295,27 @@ typedef iSinglet<Integer > TInteger;
|
||||
typedef Lattice<vColourMatrix> LatticeColourMatrix;
|
||||
typedef Lattice<vColourMatrixF> LatticeColourMatrixF;
|
||||
typedef Lattice<vColourMatrixD> LatticeColourMatrixD;
|
||||
typedef Lattice<vColourMatrixD2> LatticeColourMatrixD2;
|
||||
|
||||
typedef Lattice<vSpinMatrix> LatticeSpinMatrix;
|
||||
typedef Lattice<vSpinMatrixF> LatticeSpinMatrixF;
|
||||
typedef Lattice<vSpinMatrixD> LatticeSpinMatrixD;
|
||||
typedef Lattice<vSpinMatrixD2> LatticeSpinMatrixD2;
|
||||
|
||||
typedef Lattice<vSpinColourMatrix> LatticeSpinColourMatrix;
|
||||
typedef Lattice<vSpinColourMatrixF> LatticeSpinColourMatrixF;
|
||||
typedef Lattice<vSpinColourMatrixD> LatticeSpinColourMatrixD;
|
||||
typedef Lattice<vSpinColourMatrixD2> LatticeSpinColourMatrixD2;
|
||||
|
||||
typedef Lattice<vSpinColourSpinColourMatrix> LatticeSpinColourSpinColourMatrix;
|
||||
typedef Lattice<vSpinColourSpinColourMatrixF> LatticeSpinColourSpinColourMatrixF;
|
||||
typedef Lattice<vSpinColourSpinColourMatrixD> LatticeSpinColourSpinColourMatrixD;
|
||||
typedef Lattice<vSpinColourSpinColourMatrixD2> LatticeSpinColourSpinColourMatrixD2;
|
||||
|
||||
typedef Lattice<vLorentzColourMatrix> LatticeLorentzColourMatrix;
|
||||
typedef Lattice<vLorentzColourMatrixF> LatticeLorentzColourMatrixF;
|
||||
typedef Lattice<vLorentzColourMatrixD> LatticeLorentzColourMatrixD;
|
||||
typedef Lattice<vLorentzColourMatrixD2> LatticeLorentzColourMatrixD2;
|
||||
|
||||
typedef Lattice<vLorentzComplex> LatticeLorentzComplex;
|
||||
typedef Lattice<vLorentzComplexF> LatticeLorentzComplexF;
|
||||
@@ -296,26 +325,32 @@ typedef Lattice<vLorentzComplexD> LatticeLorentzComplexD;
|
||||
typedef Lattice<vDoubleStoredColourMatrix> LatticeDoubleStoredColourMatrix;
|
||||
typedef Lattice<vDoubleStoredColourMatrixF> LatticeDoubleStoredColourMatrixF;
|
||||
typedef Lattice<vDoubleStoredColourMatrixD> LatticeDoubleStoredColourMatrixD;
|
||||
typedef Lattice<vDoubleStoredColourMatrixD2> LatticeDoubleStoredColourMatrixD2;
|
||||
|
||||
typedef Lattice<vSpinVector> LatticeSpinVector;
|
||||
typedef Lattice<vSpinVectorF> LatticeSpinVectorF;
|
||||
typedef Lattice<vSpinVectorD> LatticeSpinVectorD;
|
||||
typedef Lattice<vSpinVectorD2> LatticeSpinVectorD2;
|
||||
|
||||
typedef Lattice<vColourVector> LatticeColourVector;
|
||||
typedef Lattice<vColourVectorF> LatticeColourVectorF;
|
||||
typedef Lattice<vColourVectorD> LatticeColourVectorD;
|
||||
typedef Lattice<vColourVectorD2> LatticeColourVectorD2;
|
||||
|
||||
typedef Lattice<vSpinColourVector> LatticeSpinColourVector;
|
||||
typedef Lattice<vSpinColourVectorF> LatticeSpinColourVectorF;
|
||||
typedef Lattice<vSpinColourVectorD> LatticeSpinColourVectorD;
|
||||
typedef Lattice<vSpinColourVectorD2> LatticeSpinColourVectorD2;
|
||||
|
||||
typedef Lattice<vHalfSpinVector> LatticeHalfSpinVector;
|
||||
typedef Lattice<vHalfSpinVectorF> LatticeHalfSpinVectorF;
|
||||
typedef Lattice<vHalfSpinVectorD> LatticeHalfSpinVectorD;
|
||||
typedef Lattice<vHalfSpinVectorD2> LatticeHalfSpinVectorD2;
|
||||
|
||||
typedef Lattice<vHalfSpinColourVector> LatticeHalfSpinColourVector;
|
||||
typedef Lattice<vHalfSpinColourVectorF> LatticeHalfSpinColourVectorF;
|
||||
typedef Lattice<vHalfSpinColourVectorD> LatticeHalfSpinColourVectorD;
|
||||
typedef Lattice<vHalfSpinColourVectorD2> LatticeHalfSpinColourVectorD2;
|
||||
|
||||
typedef Lattice<vTReal> LatticeReal;
|
||||
typedef Lattice<vTRealF> LatticeRealF;
|
||||
@@ -324,6 +359,7 @@ typedef Lattice<vTRealD> LatticeRealD;
|
||||
typedef Lattice<vTComplex> LatticeComplex;
|
||||
typedef Lattice<vTComplexF> LatticeComplexF;
|
||||
typedef Lattice<vTComplexD> LatticeComplexD;
|
||||
typedef Lattice<vTComplexD2> LatticeComplexD2;
|
||||
|
||||
typedef Lattice<vTInteger> LatticeInteger; // Predicates for "where"
|
||||
|
||||
@@ -334,124 +370,39 @@ typedef Lattice<vTInteger> LatticeInteger; // Predicates for "where"
|
||||
typedef LatticeHalfSpinColourVector LatticeHalfFermion;
|
||||
typedef LatticeHalfSpinColourVectorF LatticeHalfFermionF;
|
||||
typedef LatticeHalfSpinColourVectorD LatticeHalfFermionD;
|
||||
typedef LatticeHalfSpinColourVectorD2 LatticeHalfFermionD2;
|
||||
|
||||
typedef LatticeSpinColourVector LatticeFermion;
|
||||
typedef LatticeSpinColourVectorF LatticeFermionF;
|
||||
typedef LatticeSpinColourVectorD LatticeFermionD;
|
||||
typedef LatticeSpinColourVectorD2 LatticeFermionD2;
|
||||
|
||||
typedef LatticeSpinColourMatrix LatticePropagator;
|
||||
typedef LatticeSpinColourMatrixF LatticePropagatorF;
|
||||
typedef LatticeSpinColourMatrixD LatticePropagatorD;
|
||||
typedef LatticeSpinColourMatrixD2 LatticePropagatorD2;
|
||||
|
||||
typedef LatticeLorentzColourMatrix LatticeGaugeField;
|
||||
typedef LatticeLorentzColourMatrixF LatticeGaugeFieldF;
|
||||
typedef LatticeLorentzColourMatrixD LatticeGaugeFieldD;
|
||||
typedef LatticeLorentzColourMatrixD2 LatticeGaugeFieldD2;
|
||||
|
||||
typedef LatticeDoubleStoredColourMatrix LatticeDoubledGaugeField;
|
||||
typedef LatticeDoubleStoredColourMatrixF LatticeDoubledGaugeFieldF;
|
||||
typedef LatticeDoubleStoredColourMatrixD LatticeDoubledGaugeFieldD;
|
||||
typedef LatticeDoubleStoredColourMatrixD2 LatticeDoubledGaugeFieldD2;
|
||||
|
||||
template<class GF> using LorentzScalar = Lattice<iScalar<typename GF::vector_object::element> >;
|
||||
|
||||
typedef Lattice<vColourVector> LatticeStaggeredFermion;
|
||||
typedef Lattice<vColourVectorF> LatticeStaggeredFermionF;
|
||||
typedef Lattice<vColourVectorD> LatticeStaggeredFermionD;
|
||||
typedef Lattice<vColourVectorD2> LatticeStaggeredFermionD2;
|
||||
|
||||
typedef Lattice<vColourMatrix> LatticeStaggeredPropagator;
|
||||
typedef Lattice<vColourMatrixF> LatticeStaggeredPropagatorF;
|
||||
typedef Lattice<vColourMatrixD> LatticeStaggeredPropagatorD;
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// Lexicographic lattice types: Nsimd()==1 containers of the same tensors.
|
||||
// Single and double precision only; no default precision alias.
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Site objects over the width one simd types
|
||||
typedef iSpinMatrix<sComplexF> sSpinMatrixF;
|
||||
typedef iSpinMatrix<sComplexD> sSpinMatrixD;
|
||||
typedef iColourMatrix<sComplexF> sColourMatrixF;
|
||||
typedef iColourMatrix<sComplexD> sColourMatrixD;
|
||||
typedef iSpinColourMatrix<sComplexF> sSpinColourMatrixF;
|
||||
typedef iSpinColourMatrix<sComplexD> sSpinColourMatrixD;
|
||||
typedef iSpinColourSpinColourMatrix<sComplexF> sSpinColourSpinColourMatrixF;
|
||||
typedef iSpinColourSpinColourMatrix<sComplexD> sSpinColourSpinColourMatrixD;
|
||||
typedef iLorentzColourMatrix<sComplexF> sLorentzColourMatrixF;
|
||||
typedef iLorentzColourMatrix<sComplexD> sLorentzColourMatrixD;
|
||||
typedef iLorentzComplex<sComplexF> sLorentzComplexF;
|
||||
typedef iLorentzComplex<sComplexD> sLorentzComplexD;
|
||||
typedef iDoubleStoredColourMatrix<sComplexF> sDoubleStoredColourMatrixF;
|
||||
typedef iDoubleStoredColourMatrix<sComplexD> sDoubleStoredColourMatrixD;
|
||||
typedef iGparityFlavourMatrix<sComplexF> sGparityFlavourMatrixF;
|
||||
typedef iGparityFlavourMatrix<sComplexD> sGparityFlavourMatrixD;
|
||||
typedef iSpinVector<sComplexF> sSpinVectorF;
|
||||
typedef iSpinVector<sComplexD> sSpinVectorD;
|
||||
typedef iColourVector<sComplexF> sColourVectorF;
|
||||
typedef iColourVector<sComplexD> sColourVectorD;
|
||||
typedef iSpinColourVector<sComplexF> sSpinColourVectorF;
|
||||
typedef iSpinColourVector<sComplexD> sSpinColourVectorD;
|
||||
typedef iHalfSpinVector<sComplexF> sHalfSpinVectorF;
|
||||
typedef iHalfSpinVector<sComplexD> sHalfSpinVectorD;
|
||||
typedef iHalfSpinColourVector<sComplexF> sHalfSpinColourVectorF;
|
||||
typedef iHalfSpinColourVector<sComplexD> sHalfSpinColourVectorD;
|
||||
typedef iGparityFlavourVector<sComplexF> sGparityFlavourVectorF;
|
||||
typedef iGparityFlavourVector<sComplexD> sGparityFlavourVectorD;
|
||||
typedef iSinglet<sComplexF> sTComplexF;
|
||||
typedef iSinglet<sComplexD> sTComplexD;
|
||||
typedef iSinglet<sRealF> sTRealF;
|
||||
typedef iSinglet<sRealD> sTRealD;
|
||||
typedef iSinglet<sInteger> sTInteger;
|
||||
|
||||
// Lattices of these
|
||||
typedef Lattice<sColourMatrixF> lexLatticeColourMatrixF;
|
||||
typedef Lattice<sColourMatrixD> lexLatticeColourMatrixD;
|
||||
typedef Lattice<sSpinMatrixF> lexLatticeSpinMatrixF;
|
||||
typedef Lattice<sSpinMatrixD> lexLatticeSpinMatrixD;
|
||||
typedef Lattice<sSpinColourMatrixF> lexLatticeSpinColourMatrixF;
|
||||
typedef Lattice<sSpinColourMatrixD> lexLatticeSpinColourMatrixD;
|
||||
typedef Lattice<sSpinColourSpinColourMatrixF> lexLatticeSpinColourSpinColourMatrixF;
|
||||
typedef Lattice<sSpinColourSpinColourMatrixD> lexLatticeSpinColourSpinColourMatrixD;
|
||||
typedef Lattice<sLorentzColourMatrixF> lexLatticeLorentzColourMatrixF;
|
||||
typedef Lattice<sLorentzColourMatrixD> lexLatticeLorentzColourMatrixD;
|
||||
typedef Lattice<sLorentzComplexF> lexLatticeLorentzComplexF;
|
||||
typedef Lattice<sLorentzComplexD> lexLatticeLorentzComplexD;
|
||||
typedef Lattice<sDoubleStoredColourMatrixF> lexLatticeDoubleStoredColourMatrixF;
|
||||
typedef Lattice<sDoubleStoredColourMatrixD> lexLatticeDoubleStoredColourMatrixD;
|
||||
typedef Lattice<sSpinVectorF> lexLatticeSpinVectorF;
|
||||
typedef Lattice<sSpinVectorD> lexLatticeSpinVectorD;
|
||||
typedef Lattice<sColourVectorF> lexLatticeColourVectorF;
|
||||
typedef Lattice<sColourVectorD> lexLatticeColourVectorD;
|
||||
typedef Lattice<sSpinColourVectorF> lexLatticeSpinColourVectorF;
|
||||
typedef Lattice<sSpinColourVectorD> lexLatticeSpinColourVectorD;
|
||||
typedef Lattice<sHalfSpinVectorF> lexLatticeHalfSpinVectorF;
|
||||
typedef Lattice<sHalfSpinVectorD> lexLatticeHalfSpinVectorD;
|
||||
typedef Lattice<sHalfSpinColourVectorF> lexLatticeHalfSpinColourVectorF;
|
||||
typedef Lattice<sHalfSpinColourVectorD> lexLatticeHalfSpinColourVectorD;
|
||||
typedef Lattice<sTRealF> lexLatticeRealF;
|
||||
typedef Lattice<sTRealD> lexLatticeRealD;
|
||||
typedef Lattice<sTComplexF> lexLatticeComplexF;
|
||||
typedef Lattice<sTComplexD> lexLatticeComplexD;
|
||||
typedef Lattice<sTInteger> lexLatticeInteger;
|
||||
typedef Lattice<sColourVectorF> lexLatticeStaggeredFermionF;
|
||||
typedef Lattice<sColourVectorD> lexLatticeStaggeredFermionD;
|
||||
typedef Lattice<sColourMatrixF> lexLatticeStaggeredPropagatorF;
|
||||
typedef Lattice<sColourMatrixD> lexLatticeStaggeredPropagatorD;
|
||||
|
||||
// Physical names for things
|
||||
typedef lexLatticeHalfSpinColourVectorF lexLatticeHalfFermionF;
|
||||
typedef lexLatticeHalfSpinColourVectorD lexLatticeHalfFermionD;
|
||||
typedef lexLatticeSpinColourVectorF lexLatticeFermionF;
|
||||
typedef lexLatticeSpinColourVectorD lexLatticeFermionD;
|
||||
typedef lexLatticeSpinColourMatrixF lexLatticePropagatorF;
|
||||
typedef lexLatticeSpinColourMatrixD lexLatticePropagatorD;
|
||||
typedef lexLatticeLorentzColourMatrixF lexLatticeGaugeFieldF;
|
||||
typedef lexLatticeLorentzColourMatrixD lexLatticeGaugeFieldD;
|
||||
typedef lexLatticeDoubleStoredColourMatrixF lexLatticeDoubledGaugeFieldF;
|
||||
typedef lexLatticeDoubleStoredColourMatrixD lexLatticeDoubledGaugeFieldD;
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// End lexicographic lattice types
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
typedef Lattice<vColourMatrixD2> LatticeStaggeredPropagatorD2;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// Peek and Poke named after physics attributes
|
||||
|
||||
@@ -143,8 +143,6 @@ public:
|
||||
static int getNMAX(Lattice<iImplClover<vComplexD2>> &t, RealD R) {return getNMAX(1e-12,R);}
|
||||
static int getNMAX(Lattice<iImplClover<vComplexD>> &t, RealD R) {return getNMAX(1e-12,R);}
|
||||
static int getNMAX(Lattice<iImplClover<vComplexF>> &t, RealD R) {return getNMAX(1e-6,R);}
|
||||
static int getNMAX(Lattice<iImplClover<sComplexD>> &t, RealD R) {return getNMAX(1e-12,R);}
|
||||
static int getNMAX(Lattice<iImplClover<sComplexF>> &t, RealD R) {return getNMAX(1e-6,R);}
|
||||
|
||||
static void Instantiate(CloverField& Clover, CloverField& CloverInv, RealD csw_t, RealD diag_mass) {
|
||||
GridBase* grid = Clover.Grid();
|
||||
@@ -270,8 +268,6 @@ public:
|
||||
|
||||
static int getNMAX(Lattice<iImplClover<vComplexD>> &t, RealD R) {return getNMAX(1e-12,R);}
|
||||
static int getNMAX(Lattice<iImplClover<vComplexF>> &t, RealD R) {return getNMAX(1e-6,R);}
|
||||
static int getNMAX(Lattice<iImplClover<sComplexD>> &t, RealD R) {return getNMAX(1e-12,R);}
|
||||
static int getNMAX(Lattice<iImplClover<sComplexF>> &t, RealD R) {return getNMAX(1e-6,R);}
|
||||
|
||||
static void InstantiateClover(CloverField& Clover, CloverField& CloverInv, RealD csw_t, RealD diag_mass) {
|
||||
|
||||
|
||||
@@ -40,12 +40,15 @@ public:
|
||||
static const int Dimension = Representation::Dimension;
|
||||
static const bool isFundamental = Representation::isFundamental;
|
||||
static const bool LsVectorised=true;
|
||||
static const int Nhcs = Options::Nhcs;
|
||||
|
||||
typedef typename Options::_Coeff_t Coeff_t;
|
||||
typedef typename Options::template PrecisionMapper<Simd>::LowerPrecVector SimdL;
|
||||
|
||||
template <typename vtype> using iImplSpinor = iScalar<iVector<iVector<vtype, Dimension>, Ns> >;
|
||||
template <typename vtype> using iImplPropagator = iScalar<iMatrix<iMatrix<vtype, Dimension>, Ns> >;
|
||||
template <typename vtype> using iImplHalfSpinor = iScalar<iVector<iVector<vtype, Dimension>, Nhs> >;
|
||||
template <typename vtype> using iImplHalfCommSpinor = iScalar<iVector<iVector<vtype, Dimension>, Nhcs> >;
|
||||
template <typename vtype> using iImplDoubledGaugeField = iVector<iScalar<iMatrix<vtype, Dimension> >, Nds>;
|
||||
template <typename vtype> using iImplGaugeField = iVector<iScalar<iMatrix<vtype, Dimension> >, Nd>;
|
||||
template <typename vtype> using iImplGaugeLink = iScalar<iScalar<iMatrix<vtype, Dimension> > >;
|
||||
@@ -53,6 +56,7 @@ public:
|
||||
typedef iImplSpinor<Simd> SiteSpinor;
|
||||
typedef iImplPropagator<Simd> SitePropagator;
|
||||
typedef iImplHalfSpinor<Simd> SiteHalfSpinor;
|
||||
typedef iImplHalfCommSpinor<SimdL> SiteHalfCommSpinor;
|
||||
typedef Lattice<SiteSpinor> FermionField;
|
||||
typedef Lattice<SitePropagator> PropagatorField;
|
||||
|
||||
@@ -64,7 +68,7 @@ public:
|
||||
typedef iImplGaugeLink<typename Simd::scalar_type> SiteScalarGaugeLink; // scalar
|
||||
typedef Lattice<SiteDoubledGaugeField> DoubledGaugeField;
|
||||
|
||||
typedef WilsonCompressor<SiteHalfSpinor, SiteSpinor> Compressor;
|
||||
typedef WilsonCompressor<SiteHalfCommSpinor,SiteHalfSpinor, SiteSpinor> Compressor;
|
||||
typedef WilsonImplParams ImplParams;
|
||||
typedef WilsonStencil<SiteSpinor, SiteHalfSpinor,ImplParams> StencilImpl;
|
||||
typedef typename StencilImpl::View_type StencilView;
|
||||
@@ -197,8 +201,16 @@ typedef DomainWallVec5dImpl<vComplex ,FundamentalRepresentation, CoeffReal> Doma
|
||||
typedef DomainWallVec5dImpl<vComplexF,FundamentalRepresentation, CoeffReal> DomainWallVec5dImplF; // Float
|
||||
typedef DomainWallVec5dImpl<vComplexD,FundamentalRepresentation, CoeffReal> DomainWallVec5dImplD; // Double
|
||||
|
||||
typedef DomainWallVec5dImpl<vComplex ,FundamentalRepresentation, CoeffRealHalfComms> DomainWallVec5dImplRL; // Real.. whichever prec
|
||||
typedef DomainWallVec5dImpl<vComplexF,FundamentalRepresentation, CoeffRealHalfComms> DomainWallVec5dImplFH; // Float
|
||||
typedef DomainWallVec5dImpl<vComplexD,FundamentalRepresentation, CoeffRealHalfComms> DomainWallVec5dImplDF; // Double
|
||||
|
||||
typedef DomainWallVec5dImpl<vComplex ,FundamentalRepresentation,CoeffComplex> ZDomainWallVec5dImplR; // Real.. whichever prec
|
||||
typedef DomainWallVec5dImpl<vComplexF,FundamentalRepresentation,CoeffComplex> ZDomainWallVec5dImplF; // Float
|
||||
typedef DomainWallVec5dImpl<vComplexD,FundamentalRepresentation,CoeffComplex> ZDomainWallVec5dImplD; // Double
|
||||
|
||||
typedef DomainWallVec5dImpl<vComplex ,FundamentalRepresentation,CoeffComplexHalfComms> ZDomainWallVec5dImplRL; // Real.. whichever prec
|
||||
typedef DomainWallVec5dImpl<vComplexF,FundamentalRepresentation,CoeffComplexHalfComms> ZDomainWallVec5dImplFH; // Float
|
||||
typedef DomainWallVec5dImpl<vComplexD,FundamentalRepresentation,CoeffComplexHalfComms> ZDomainWallVec5dImplDF; // Double
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -114,7 +114,7 @@ NAMESPACE_CHECK(DWFutils);
|
||||
// Cayley 5d
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
//typedef WilsonFermion<WilsonImplD2> WilsonFermionD2;
|
||||
typedef WilsonFermion<WilsonImplD2> WilsonFermionD2;
|
||||
typedef WilsonFermion<WilsonImplF> WilsonFermionF;
|
||||
typedef WilsonFermion<WilsonImplD> WilsonFermionD;
|
||||
|
||||
@@ -138,7 +138,7 @@ typedef WilsonFermion<SpWilsonTwoIndexSymmetricImplF> SpWilsonTwoIndexSymmetricF
|
||||
typedef WilsonFermion<SpWilsonTwoIndexSymmetricImplD> SpWilsonTwoIndexSymmetricFermionD;
|
||||
|
||||
// Twisted mass fermion
|
||||
//typedef WilsonTMFermion<WilsonImplD2> WilsonTMFermionD2;
|
||||
typedef WilsonTMFermion<WilsonImplD2> WilsonTMFermionD2;
|
||||
typedef WilsonTMFermion<WilsonImplF> WilsonTMFermionF;
|
||||
typedef WilsonTMFermion<WilsonImplD> WilsonTMFermionD;
|
||||
|
||||
@@ -146,11 +146,11 @@ typedef WilsonTMFermion<WilsonImplD> WilsonTMFermionD;
|
||||
template <typename WImpl> using WilsonClover = WilsonCloverFermion<WImpl, CloverHelpers<WImpl>>;
|
||||
template <typename WImpl> using WilsonExpClover = WilsonCloverFermion<WImpl, ExpCloverHelpers<WImpl>>;
|
||||
|
||||
//typedef WilsonClover<WilsonImplD2> WilsonCloverFermionD2;
|
||||
typedef WilsonClover<WilsonImplD2> WilsonCloverFermionD2;
|
||||
typedef WilsonClover<WilsonImplF> WilsonCloverFermionF;
|
||||
typedef WilsonClover<WilsonImplD> WilsonCloverFermionD;
|
||||
|
||||
//typedef WilsonExpClover<WilsonImplD2> WilsonExpCloverFermionD2;
|
||||
typedef WilsonExpClover<WilsonImplD2> WilsonExpCloverFermionD2;
|
||||
typedef WilsonExpClover<WilsonImplF> WilsonExpCloverFermionF;
|
||||
typedef WilsonExpClover<WilsonImplD> WilsonExpCloverFermionD;
|
||||
|
||||
@@ -168,15 +168,15 @@ template <typename WImpl> using CompactWilsonClover = CompactWilsonCloverFermion
|
||||
template <typename WImpl> using CompactWilsonClover5D = CompactWilsonCloverFermion5D<WImpl, CompactCloverHelpers<WImpl>>;
|
||||
template <typename WImpl> using CompactWilsonExpClover = CompactWilsonCloverFermion<WImpl, CompactExpCloverHelpers<WImpl>>;
|
||||
|
||||
//typedef CompactWilsonClover<WilsonImplD2> CompactWilsonCloverFermionD2;
|
||||
typedef CompactWilsonClover<WilsonImplD2> CompactWilsonCloverFermionD2;
|
||||
typedef CompactWilsonClover<WilsonImplF> CompactWilsonCloverFermionF;
|
||||
typedef CompactWilsonClover<WilsonImplD> CompactWilsonCloverFermionD;
|
||||
|
||||
//typedef CompactWilsonClover5D<WilsonImplD2> CompactWilsonCloverFermion5DD2;
|
||||
typedef CompactWilsonClover5D<WilsonImplD2> CompactWilsonCloverFermion5DD2;
|
||||
typedef CompactWilsonClover5D<WilsonImplF> CompactWilsonCloverFermion5DF;
|
||||
typedef CompactWilsonClover5D<WilsonImplD> CompactWilsonCloverFermion5DD;
|
||||
|
||||
//typedef CompactWilsonExpClover<WilsonImplD2> CompactWilsonExpCloverFermionD2;
|
||||
typedef CompactWilsonExpClover<WilsonImplD2> CompactWilsonExpCloverFermionD2;
|
||||
typedef CompactWilsonExpClover<WilsonImplF> CompactWilsonExpCloverFermionF;
|
||||
typedef CompactWilsonExpClover<WilsonImplD> CompactWilsonExpCloverFermionD;
|
||||
|
||||
@@ -192,56 +192,56 @@ typedef CompactWilsonClover<WilsonTwoIndexAntiSymmetricImplD> CompactWilsonClove
|
||||
// Domain Wall fermions
|
||||
typedef DomainWallFermion<WilsonImplF> DomainWallFermionF;
|
||||
typedef DomainWallFermion<WilsonImplD> DomainWallFermionD;
|
||||
//typedef DomainWallFermion<WilsonImplD2> DomainWallFermionD2;
|
||||
typedef DomainWallFermion<WilsonImplD2> DomainWallFermionD2;
|
||||
|
||||
//typedef DomainWallEOFAFermion<WilsonImplD2> DomainWallEOFAFermionD2;
|
||||
typedef DomainWallEOFAFermion<WilsonImplD2> DomainWallEOFAFermionD2;
|
||||
typedef DomainWallEOFAFermion<WilsonImplF> DomainWallEOFAFermionF;
|
||||
typedef DomainWallEOFAFermion<WilsonImplD> DomainWallEOFAFermionD;
|
||||
|
||||
//typedef MobiusFermion<WilsonImplD2> MobiusFermionD2;
|
||||
typedef MobiusFermion<WilsonImplD2> MobiusFermionD2;
|
||||
typedef MobiusFermion<WilsonImplF> MobiusFermionF;
|
||||
typedef MobiusFermion<WilsonImplD> MobiusFermionD;
|
||||
|
||||
//typedef MobiusEOFAFermion<WilsonImplD2> MobiusEOFAFermionD2;
|
||||
typedef MobiusEOFAFermion<WilsonImplD2> MobiusEOFAFermionD2;
|
||||
typedef MobiusEOFAFermion<WilsonImplF> MobiusEOFAFermionF;
|
||||
typedef MobiusEOFAFermion<WilsonImplD> MobiusEOFAFermionD;
|
||||
|
||||
//typedef ZMobiusFermion<ZWilsonImplD2> ZMobiusFermionD2;
|
||||
typedef ZMobiusFermion<ZWilsonImplD2> ZMobiusFermionD2;
|
||||
typedef ZMobiusFermion<ZWilsonImplF> ZMobiusFermionF;
|
||||
typedef ZMobiusFermion<ZWilsonImplD> ZMobiusFermionD;
|
||||
|
||||
//typedef ScaledShamirFermion<WilsonImplD2> ScaledShamirFermionD2;
|
||||
typedef ScaledShamirFermion<WilsonImplD2> ScaledShamirFermionD2;
|
||||
typedef ScaledShamirFermion<WilsonImplF> ScaledShamirFermionF;
|
||||
typedef ScaledShamirFermion<WilsonImplD> ScaledShamirFermionD;
|
||||
|
||||
//typedef MobiusZolotarevFermion<WilsonImplD2> MobiusZolotarevFermionD2;
|
||||
typedef MobiusZolotarevFermion<WilsonImplD2> MobiusZolotarevFermionD2;
|
||||
typedef MobiusZolotarevFermion<WilsonImplF> MobiusZolotarevFermionF;
|
||||
typedef MobiusZolotarevFermion<WilsonImplD> MobiusZolotarevFermionD;
|
||||
//typedef ShamirZolotarevFermion<WilsonImplD2> ShamirZolotarevFermionD2;
|
||||
typedef ShamirZolotarevFermion<WilsonImplD2> ShamirZolotarevFermionD2;
|
||||
typedef ShamirZolotarevFermion<WilsonImplF> ShamirZolotarevFermionF;
|
||||
typedef ShamirZolotarevFermion<WilsonImplD> ShamirZolotarevFermionD;
|
||||
|
||||
//typedef OverlapWilsonCayleyTanhFermion<WilsonImplD2> OverlapWilsonCayleyTanhFermionD2;
|
||||
typedef OverlapWilsonCayleyTanhFermion<WilsonImplD2> OverlapWilsonCayleyTanhFermionD2;
|
||||
typedef OverlapWilsonCayleyTanhFermion<WilsonImplF> OverlapWilsonCayleyTanhFermionF;
|
||||
typedef OverlapWilsonCayleyTanhFermion<WilsonImplD> OverlapWilsonCayleyTanhFermionD;
|
||||
//typedef OverlapWilsonCayleyZolotarevFermion<WilsonImplD2> OverlapWilsonCayleyZolotarevFermionD2;
|
||||
typedef OverlapWilsonCayleyZolotarevFermion<WilsonImplD2> OverlapWilsonCayleyZolotarevFermionD2;
|
||||
typedef OverlapWilsonCayleyZolotarevFermion<WilsonImplF> OverlapWilsonCayleyZolotarevFermionF;
|
||||
typedef OverlapWilsonCayleyZolotarevFermion<WilsonImplD> OverlapWilsonCayleyZolotarevFermionD;
|
||||
|
||||
// Continued fraction
|
||||
//typedef OverlapWilsonContFracTanhFermion<WilsonImplD2> OverlapWilsonContFracTanhFermionD2;
|
||||
typedef OverlapWilsonContFracTanhFermion<WilsonImplD2> OverlapWilsonContFracTanhFermionD2;
|
||||
typedef OverlapWilsonContFracTanhFermion<WilsonImplF> OverlapWilsonContFracTanhFermionF;
|
||||
typedef OverlapWilsonContFracTanhFermion<WilsonImplD> OverlapWilsonContFracTanhFermionD;
|
||||
//typedef OverlapWilsonContFracZolotarevFermion<WilsonImplD2> OverlapWilsonContFracZolotarevFermionD2;
|
||||
typedef OverlapWilsonContFracZolotarevFermion<WilsonImplD2> OverlapWilsonContFracZolotarevFermionD2;
|
||||
typedef OverlapWilsonContFracZolotarevFermion<WilsonImplF> OverlapWilsonContFracZolotarevFermionF;
|
||||
typedef OverlapWilsonContFracZolotarevFermion<WilsonImplD> OverlapWilsonContFracZolotarevFermionD;
|
||||
|
||||
// Partial fraction
|
||||
//typedef OverlapWilsonPartialFractionTanhFermion<WilsonImplD2> OverlapWilsonPartialFractionTanhFermionD2;
|
||||
typedef OverlapWilsonPartialFractionTanhFermion<WilsonImplD2> OverlapWilsonPartialFractionTanhFermionD2;
|
||||
typedef OverlapWilsonPartialFractionTanhFermion<WilsonImplF> OverlapWilsonPartialFractionTanhFermionF;
|
||||
typedef OverlapWilsonPartialFractionTanhFermion<WilsonImplD> OverlapWilsonPartialFractionTanhFermionD;
|
||||
|
||||
//typedef OverlapWilsonPartialFractionZolotarevFermion<WilsonImplD2> OverlapWilsonPartialFractionZolotarevFermionD2;
|
||||
typedef OverlapWilsonPartialFractionZolotarevFermion<WilsonImplD2> OverlapWilsonPartialFractionZolotarevFermionD2;
|
||||
typedef OverlapWilsonPartialFractionZolotarevFermion<WilsonImplF> OverlapWilsonPartialFractionZolotarevFermionF;
|
||||
typedef OverlapWilsonPartialFractionZolotarevFermion<WilsonImplD> OverlapWilsonPartialFractionZolotarevFermionD;
|
||||
|
||||
@@ -252,19 +252,19 @@ typedef WilsonFermion<GparityWilsonImplD> GparityWilsonFermionD;
|
||||
typedef DomainWallFermion<GparityWilsonImplF> GparityDomainWallFermionF;
|
||||
typedef DomainWallFermion<GparityWilsonImplD> GparityDomainWallFermionD;
|
||||
|
||||
//typedef DomainWallEOFAFermion<GparityWilsonImplR> GparityDomainWallEOFAFermionD2;
|
||||
typedef DomainWallEOFAFermion<GparityWilsonImplR> GparityDomainWallEOFAFermionD2;
|
||||
typedef DomainWallEOFAFermion<GparityWilsonImplF> GparityDomainWallEOFAFermionF;
|
||||
typedef DomainWallEOFAFermion<GparityWilsonImplD> GparityDomainWallEOFAFermionD;
|
||||
|
||||
//typedef WilsonTMFermion<GparityWilsonImplR> GparityWilsonTMFermionD2;
|
||||
typedef WilsonTMFermion<GparityWilsonImplR> GparityWilsonTMFermionD2;
|
||||
typedef WilsonTMFermion<GparityWilsonImplF> GparityWilsonTMFermionF;
|
||||
typedef WilsonTMFermion<GparityWilsonImplD> GparityWilsonTMFermionD;
|
||||
|
||||
//typedef MobiusFermion<GparityWilsonImplR> GparityMobiusFermionD2;
|
||||
typedef MobiusFermion<GparityWilsonImplR> GparityMobiusFermionD2;
|
||||
typedef MobiusFermion<GparityWilsonImplF> GparityMobiusFermionF;
|
||||
typedef MobiusFermion<GparityWilsonImplD> GparityMobiusFermionD;
|
||||
|
||||
//typedef MobiusEOFAFermion<GparityWilsonImplR> GparityMobiusEOFAFermionD2;
|
||||
typedef MobiusEOFAFermion<GparityWilsonImplR> GparityMobiusEOFAFermionD2;
|
||||
typedef MobiusEOFAFermion<GparityWilsonImplF> GparityMobiusEOFAFermionF;
|
||||
typedef MobiusEOFAFermion<GparityWilsonImplD> GparityMobiusEOFAFermionD;
|
||||
|
||||
|
||||
@@ -88,14 +88,51 @@ NAMESPACE_BEGIN(Grid);
|
||||
// }
|
||||
//////////////////////////////////////////////
|
||||
|
||||
template <class T> struct SamePrecisionMapper {
|
||||
typedef T HigherPrecVector ;
|
||||
typedef T LowerPrecVector ;
|
||||
};
|
||||
template <class T> struct LowerPrecisionMapper { };
|
||||
template <> struct LowerPrecisionMapper<vRealF> {
|
||||
typedef vRealF HigherPrecVector ;
|
||||
typedef vRealH LowerPrecVector ;
|
||||
};
|
||||
template <> struct LowerPrecisionMapper<vRealD> {
|
||||
typedef vRealD HigherPrecVector ;
|
||||
typedef vRealF LowerPrecVector ;
|
||||
};
|
||||
template <> struct LowerPrecisionMapper<vComplexF> {
|
||||
typedef vComplexF HigherPrecVector ;
|
||||
typedef vComplexH LowerPrecVector ;
|
||||
};
|
||||
template <> struct LowerPrecisionMapper<vComplexD> {
|
||||
typedef vComplexD HigherPrecVector ;
|
||||
typedef vComplexF LowerPrecVector ;
|
||||
};
|
||||
|
||||
struct CoeffReal {
|
||||
public:
|
||||
typedef RealD _Coeff_t;
|
||||
static const int Nhcs = 2;
|
||||
template<class Simd> using PrecisionMapper = SamePrecisionMapper<Simd>;
|
||||
};
|
||||
struct CoeffRealHalfComms {
|
||||
public:
|
||||
typedef RealD _Coeff_t;
|
||||
static const int Nhcs = 1;
|
||||
template<class Simd> using PrecisionMapper = LowerPrecisionMapper<Simd>;
|
||||
};
|
||||
struct CoeffComplex {
|
||||
public:
|
||||
typedef ComplexD _Coeff_t;
|
||||
static const int Nhcs = 2;
|
||||
template<class Simd> using PrecisionMapper = SamePrecisionMapper<Simd>;
|
||||
};
|
||||
struct CoeffComplexHalfComms {
|
||||
public:
|
||||
typedef ComplexD _Coeff_t;
|
||||
static const int Nhcs = 1;
|
||||
template<class Simd> using PrecisionMapper = LowerPrecisionMapper<Simd>;
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -48,6 +48,7 @@ public:
|
||||
|
||||
static const int Dimension = Representation::Dimension;
|
||||
static const bool isFundamental = Representation::isFundamental;
|
||||
static const int Nhcs = Options::Nhcs;
|
||||
static const bool LsVectorised=false;
|
||||
static const bool isGparity=true;
|
||||
|
||||
@@ -55,15 +56,18 @@ public:
|
||||
INHERIT_GIMPL_TYPES(Gimpl);
|
||||
|
||||
typedef typename Options::_Coeff_t Coeff_t;
|
||||
typedef typename Options::template PrecisionMapper<Simd>::LowerPrecVector SimdL;
|
||||
|
||||
template <typename vtype> using iImplSpinor = iVector<iVector<iVector<vtype, Dimension>, Ns>, Ngp>;
|
||||
template <typename vtype> using iImplPropagator = iMatrix<iMatrix<iMatrix<vtype, Dimension>, Ns>, Ngp>;
|
||||
template <typename vtype> using iImplHalfSpinor = iVector<iVector<iVector<vtype, Dimension>, Nhs>, Ngp>;
|
||||
template <typename vtype> using iImplHalfCommSpinor = iVector<iVector<iVector<vtype, Dimension>, Nhcs>, Ngp>;
|
||||
template <typename vtype> using iImplDoubledGaugeField = iVector<iVector<iScalar<iMatrix<vtype, Dimension> >, Nds>, Ngp>;
|
||||
|
||||
typedef iImplSpinor<Simd> SiteSpinor;
|
||||
typedef iImplPropagator<Simd> SitePropagator;
|
||||
typedef iImplHalfSpinor<Simd> SiteHalfSpinor;
|
||||
typedef iImplHalfCommSpinor<SimdL> SiteHalfCommSpinor;
|
||||
typedef iImplDoubledGaugeField<Simd> SiteDoubledGaugeField;
|
||||
|
||||
typedef Lattice<SiteSpinor> FermionField;
|
||||
@@ -71,7 +75,7 @@ public:
|
||||
typedef Lattice<SiteDoubledGaugeField> DoubledGaugeField;
|
||||
|
||||
typedef GparityWilsonImplParams ImplParams;
|
||||
typedef WilsonCompressor<SiteHalfSpinor, SiteSpinor> Compressor;
|
||||
typedef WilsonCompressor<SiteHalfCommSpinor,SiteHalfSpinor, SiteSpinor> Compressor;
|
||||
typedef WilsonStencil<SiteSpinor, SiteHalfSpinor, ImplParams> StencilImpl;
|
||||
typedef typename StencilImpl::View_type StencilView;
|
||||
|
||||
@@ -404,5 +408,9 @@ public:
|
||||
typedef GparityWilsonImpl<vComplex , FundamentalRepresentation,CoeffReal> GparityWilsonImplR; // Real.. whichever prec
|
||||
typedef GparityWilsonImpl<vComplexF, FundamentalRepresentation,CoeffReal> GparityWilsonImplF; // Float
|
||||
typedef GparityWilsonImpl<vComplexD, FundamentalRepresentation,CoeffReal> GparityWilsonImplD; // Double
|
||||
|
||||
//typedef GparityWilsonImpl<vComplex , FundamentalRepresentation,CoeffRealHalfComms> GparityWilsonImplRL; // Real.. whichever prec
|
||||
//typedef GparityWilsonImpl<vComplexF, FundamentalRepresentation,CoeffRealHalfComms> GparityWilsonImplFH; // Float
|
||||
//typedef GparityWilsonImpl<vComplexD, FundamentalRepresentation,CoeffRealHalfComms> GparityWilsonImplDF; // Double
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -176,13 +176,4 @@ typedef StaggeredImpl<vComplex, FundamentalRepresentation > StaggeredImplR; /
|
||||
typedef StaggeredImpl<vComplexF, FundamentalRepresentation > StaggeredImplF; // Float
|
||||
typedef StaggeredImpl<vComplexD, FundamentalRepresentation > StaggeredImplD; // Double
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// Lexicographic staggered implementations
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
typedef StaggeredImpl<sComplexF, FundamentalRepresentation > lexStaggeredImplF;
|
||||
typedef StaggeredImpl<sComplexD, FundamentalRepresentation > lexStaggeredImplD;
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// End lexicographic staggered implementations
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -38,7 +38,7 @@ NAMESPACE_BEGIN(Grid);
|
||||
|
||||
|
||||
//Could make FaceGather a template param, but then behaviour is runtime not compile time
|
||||
template<class _Hspinor,class _Spinor, class projector>
|
||||
template<class _HCspinor,class _Hspinor,class _Spinor, class projector>
|
||||
class WilsonCompressorTemplate : public FaceGatherSimple
|
||||
{
|
||||
public:
|
||||
@@ -53,11 +53,13 @@ public:
|
||||
|
||||
typedef _Spinor SiteSpinor;
|
||||
typedef _Hspinor SiteHalfSpinor;
|
||||
typedef typename SiteHalfSpinor::vector_type vector_type;
|
||||
constexpr static int Nw=sizeof(SiteHalfSpinor)/sizeof(vector_type);
|
||||
typedef _HCspinor SiteHalfCommSpinor;
|
||||
typedef typename SiteHalfCommSpinor::vector_type vComplexLow;
|
||||
typedef typename SiteHalfSpinor::vector_type vComplexHigh;
|
||||
constexpr static int Nw=sizeof(SiteHalfSpinor)/sizeof(vComplexHigh);
|
||||
|
||||
accelerator_inline int CommDatumSize(void) const {
|
||||
return sizeof(SiteHalfSpinor);
|
||||
return sizeof(SiteHalfCommSpinor);
|
||||
}
|
||||
|
||||
/*****************************************************/
|
||||
@@ -157,7 +159,7 @@ public:
|
||||
spProj(result,in); \
|
||||
} \
|
||||
}; \
|
||||
template<typename HS,typename S> using Compressor = WilsonCompressorTemplate<HS,S,Projector>;
|
||||
template<typename HCS,typename HS,typename S> using Compressor = WilsonCompressorTemplate<HCS,HS,S,Projector>;
|
||||
|
||||
DECLARE_PROJ(WilsonXpProjector,WilsonXpCompressor,spProjXp);
|
||||
DECLARE_PROJ(WilsonYpProjector,WilsonYpCompressor,spProjYp);
|
||||
@@ -186,7 +188,7 @@ public:
|
||||
}
|
||||
}
|
||||
};
|
||||
template<typename HS,typename S> using WilsonCompressor = WilsonCompressorTemplate<HS,S,WilsonProjector>;
|
||||
template<typename HCS,typename HS,typename S> using WilsonCompressor = WilsonCompressorTemplate<HCS,HS,S,WilsonProjector>;
|
||||
|
||||
// Fast comms buffer manipulation which should inline right through (avoid direction
|
||||
// dependent logic that prevents inlining
|
||||
@@ -235,6 +237,7 @@ public:
|
||||
// Use types to select the write direction by directon compressor
|
||||
typedef typename compressor::SiteSpinor SiteSpinor;
|
||||
typedef typename compressor::SiteHalfSpinor SiteHalfSpinor;
|
||||
typedef typename compressor::SiteHalfCommSpinor SiteHalfCommSpinor;
|
||||
|
||||
this->_grid->StencilBarrier();
|
||||
|
||||
@@ -242,14 +245,14 @@ public:
|
||||
|
||||
this->u_comm_offset=0;
|
||||
|
||||
WilsonXpCompressor<SiteHalfSpinor,SiteSpinor> XpCompress;
|
||||
WilsonYpCompressor<SiteHalfSpinor,SiteSpinor> YpCompress;
|
||||
WilsonZpCompressor<SiteHalfSpinor,SiteSpinor> ZpCompress;
|
||||
WilsonTpCompressor<SiteHalfSpinor,SiteSpinor> TpCompress;
|
||||
WilsonXmCompressor<SiteHalfSpinor,SiteSpinor> XmCompress;
|
||||
WilsonYmCompressor<SiteHalfSpinor,SiteSpinor> YmCompress;
|
||||
WilsonZmCompressor<SiteHalfSpinor,SiteSpinor> ZmCompress;
|
||||
WilsonTmCompressor<SiteHalfSpinor,SiteSpinor> TmCompress;
|
||||
WilsonXpCompressor<SiteHalfCommSpinor,SiteHalfSpinor,SiteSpinor> XpCompress;
|
||||
WilsonYpCompressor<SiteHalfCommSpinor,SiteHalfSpinor,SiteSpinor> YpCompress;
|
||||
WilsonZpCompressor<SiteHalfCommSpinor,SiteHalfSpinor,SiteSpinor> ZpCompress;
|
||||
WilsonTpCompressor<SiteHalfCommSpinor,SiteHalfSpinor,SiteSpinor> TpCompress;
|
||||
WilsonXmCompressor<SiteHalfCommSpinor,SiteHalfSpinor,SiteSpinor> XmCompress;
|
||||
WilsonYmCompressor<SiteHalfCommSpinor,SiteHalfSpinor,SiteSpinor> YmCompress;
|
||||
WilsonZmCompressor<SiteHalfCommSpinor,SiteHalfSpinor,SiteSpinor> ZmCompress;
|
||||
WilsonTmCompressor<SiteHalfCommSpinor,SiteHalfSpinor,SiteSpinor> TmCompress;
|
||||
|
||||
int dag = compress.dag;
|
||||
int face_idx=0;
|
||||
|
||||
@@ -42,6 +42,7 @@ public:
|
||||
static const bool isFundamental = Representation::isFundamental;
|
||||
static const bool LsVectorised=false;
|
||||
static const bool isGparity=false;
|
||||
static const int Nhcs = Options::Nhcs;
|
||||
|
||||
typedef PeriodicGaugeImpl<GaugeImplTypes<S, Dimension > > Gimpl;
|
||||
INHERIT_GIMPL_TYPES(Gimpl);
|
||||
@@ -50,22 +51,25 @@ public:
|
||||
constexpr bool is_fundamental() const{return Dimension == Nc ? 1 : 0;}
|
||||
|
||||
typedef typename Options::_Coeff_t Coeff_t;
|
||||
typedef typename Options::template PrecisionMapper<Simd>::LowerPrecVector SimdL;
|
||||
|
||||
template <typename vtype> using iImplSpinor = iScalar<iVector<iVector<vtype, Dimension>, Ns> >;
|
||||
template <typename vtype> using iImplPropagator = iScalar<iMatrix<iMatrix<vtype, Dimension>, Ns> >;
|
||||
template <typename vtype> using iImplHalfSpinor = iScalar<iVector<iVector<vtype, Dimension>, Nhs> >;
|
||||
template <typename vtype> using iImplHalfCommSpinor = iScalar<iVector<iVector<vtype, Dimension>, Nhcs> >;
|
||||
template <typename vtype> using iImplDoubledGaugeField = iVector<iScalar<iMatrix<vtype, Dimension> >, Nds>;
|
||||
|
||||
typedef iImplSpinor<Simd> SiteSpinor;
|
||||
typedef iImplPropagator<Simd> SitePropagator;
|
||||
typedef iImplHalfSpinor<Simd> SiteHalfSpinor;
|
||||
typedef iImplHalfCommSpinor<SimdL> SiteHalfCommSpinor;
|
||||
typedef iImplDoubledGaugeField<Simd> SiteDoubledGaugeField;
|
||||
|
||||
typedef Lattice<SiteSpinor> FermionField;
|
||||
typedef Lattice<SitePropagator> PropagatorField;
|
||||
typedef Lattice<SiteDoubledGaugeField> DoubledGaugeField;
|
||||
|
||||
typedef WilsonCompressor<SiteHalfSpinor, SiteSpinor> Compressor;
|
||||
typedef WilsonCompressor<SiteHalfCommSpinor,SiteHalfSpinor, SiteSpinor> Compressor;
|
||||
typedef WilsonImplParams ImplParams;
|
||||
typedef WilsonStencil<SiteSpinor, SiteHalfSpinor,ImplParams> StencilImpl;
|
||||
typedef const typename StencilImpl::View_type StencilView;
|
||||
@@ -238,19 +242,12 @@ public:
|
||||
typedef WilsonImpl<vComplex, FundamentalRepresentation, CoeffReal > WilsonImplR; // Real.. whichever prec
|
||||
typedef WilsonImpl<vComplexF, FundamentalRepresentation, CoeffReal > WilsonImplF; // Float
|
||||
typedef WilsonImpl<vComplexD, FundamentalRepresentation, CoeffReal > WilsonImplD; // Double
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// Lexicographic Wilson implementations
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
typedef WilsonImpl<sComplexF, FundamentalRepresentation, CoeffReal > lexWilsonImplF;
|
||||
typedef WilsonImpl<sComplexD, FundamentalRepresentation, CoeffReal > lexWilsonImplD;
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// End lexicographic Wilson implementations
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
typedef WilsonImpl<vComplexD2, FundamentalRepresentation, CoeffReal > WilsonImplD2; // Double
|
||||
|
||||
typedef WilsonImpl<vComplex, FundamentalRepresentation, CoeffComplex > ZWilsonImplR; // Real.. whichever prec
|
||||
typedef WilsonImpl<vComplexF, FundamentalRepresentation, CoeffComplex > ZWilsonImplF; // Float
|
||||
typedef WilsonImpl<vComplexD, FundamentalRepresentation, CoeffComplex > ZWilsonImplD; // Double
|
||||
typedef WilsonImpl<vComplexD2, FundamentalRepresentation, CoeffComplex > ZWilsonImplD2; // Double
|
||||
|
||||
typedef WilsonImpl<vComplex, AdjointRepresentation, CoeffReal > WilsonAdjImplR; // Real.. whichever prec
|
||||
typedef WilsonImpl<vComplexF, AdjointRepresentation, CoeffReal > WilsonAdjImplF; // Float
|
||||
|
||||
@@ -684,7 +684,7 @@ void StaggeredKernels<Impl>::DhopSiteAsm(StencilView &st,
|
||||
#ifdef STAG_VEC5D
|
||||
// This is the single precision 5th direction vectorised kernel
|
||||
#include <Grid/simd/Intel512single.h>
|
||||
template <> inline void StaggeredKernels<StaggeredVec5dImplF>::DhopSiteAsm(StencilView &st,
|
||||
template <> void StaggeredKernels<StaggeredVec5dImplF>::DhopSiteAsm(StencilView &st,
|
||||
DoubledGaugeFieldView &U,
|
||||
DoubledGaugeFieldView &UUU,
|
||||
SiteSpinor *buf, int sF,
|
||||
@@ -739,7 +739,7 @@ template <> inline void StaggeredKernels<StaggeredVec5dImplF>::DhopSiteAsm(Stenc
|
||||
}
|
||||
|
||||
#include <Grid/simd/Intel512double.h>
|
||||
template <> inline void StaggeredKernels<StaggeredVec5dImplD>::DhopSiteAsm(StencilView &st,
|
||||
template <> void StaggeredKernels<StaggeredVec5dImplD>::DhopSiteAsm(StencilView &st,
|
||||
DoubledGaugeFieldView &U,
|
||||
DoubledGaugeFieldView &UUU,
|
||||
SiteSpinor *buf, int sF,
|
||||
@@ -825,7 +825,7 @@ template <> inline void StaggeredKernels<StaggeredVec5dImplD>::DhopSiteAsm(Stenc
|
||||
// This is the single precision 5th direction vectorised kernel
|
||||
|
||||
#include <Grid/simd/Intel512single.h>
|
||||
template <> inline void StaggeredKernels<StaggeredImplF>::DhopSiteAsm(StencilView &st,
|
||||
template <> void StaggeredKernels<StaggeredImplF>::DhopSiteAsm(StencilView &st,
|
||||
DoubledGaugeFieldView &U,
|
||||
DoubledGaugeFieldView &UUU,
|
||||
SiteSpinor *buf, int sF,
|
||||
@@ -894,7 +894,7 @@ template <> inline void StaggeredKernels<StaggeredImplF>::DhopSiteAsm(StencilVie
|
||||
}
|
||||
|
||||
#include <Grid/simd/Intel512double.h>
|
||||
template <> inline void StaggeredKernels<StaggeredImplD>::DhopSiteAsm(StencilView &st,
|
||||
template <> void StaggeredKernels<StaggeredImplD>::DhopSiteAsm(StencilView &st,
|
||||
DoubledGaugeFieldView &U,
|
||||
DoubledGaugeFieldView &UUU,
|
||||
SiteSpinor *buf, int sF,
|
||||
|
||||
@@ -29,7 +29,6 @@ directory
|
||||
#include <Grid/qcd/action/fermion/FermionCore.h>
|
||||
#include <Grid/qcd/action/fermion/implementation/StaggeredKernelsImplementation.h>
|
||||
#include <Grid/qcd/action/fermion/implementation/StaggeredKernelsHand.h>
|
||||
#include <Grid/qcd/action/fermion/implementation/StaggeredKernelsAsm.h>
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
|
||||
@@ -2,15 +2,14 @@
|
||||
|
||||
STAG_IMPL_LIST=" \
|
||||
StaggeredImplF \
|
||||
StaggeredImplD \
|
||||
lexStaggeredImplF \
|
||||
lexStaggeredImplD "
|
||||
StaggeredImplD "
|
||||
|
||||
STAG5_IMPL_LIST=""
|
||||
|
||||
WILSON_IMPL_LIST=" \
|
||||
WilsonImplF \
|
||||
WilsonImplD \
|
||||
lexWilsonImplF \
|
||||
lexWilsonImplD \
|
||||
WilsonImplD2 \
|
||||
SpWilsonImplF \
|
||||
SpWilsonImplD \
|
||||
WilsonAdjImplF \
|
||||
@@ -33,10 +32,9 @@ COMPACT_WILSON_IMPL_LIST=" \
|
||||
DWF_IMPL_LIST=" \
|
||||
WilsonImplF \
|
||||
WilsonImplD \
|
||||
lexWilsonImplF \
|
||||
lexWilsonImplD \
|
||||
WilsonImplD2 \
|
||||
ZWilsonImplF \
|
||||
ZWilsonImplD "
|
||||
ZWilsonImplD2 "
|
||||
|
||||
GDWF_IMPL_LIST=" \
|
||||
GparityWilsonImplF \
|
||||
@@ -111,3 +109,8 @@ do
|
||||
ln -f -s ../$f.cc.master $impl/$f$impl.cc
|
||||
done
|
||||
done
|
||||
|
||||
CC_LIST=" \
|
||||
ImprovedStaggeredFermion5DInstantiation \
|
||||
StaggeredKernelsInstantiation "
|
||||
|
||||
-1
@@ -1 +0,0 @@
|
||||
../ImprovedStaggeredFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../ImprovedStaggeredFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../NaiveStaggeredFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../StaggeredKernelsInstantiation.cc.master
|
||||
@@ -1 +0,0 @@
|
||||
#define IMPLEMENTATION lexStaggeredImplD
|
||||
-1
@@ -1 +0,0 @@
|
||||
../ImprovedStaggeredFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../ImprovedStaggeredFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../NaiveStaggeredFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../StaggeredKernelsInstantiation.cc.master
|
||||
@@ -1 +0,0 @@
|
||||
#define IMPLEMENTATION lexStaggeredImplF
|
||||
-1
@@ -1 +0,0 @@
|
||||
../CayleyFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../ContinuedFractionFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../DomainWallEOFAFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../MobiusEOFAFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../PartialFractionFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonCloverFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonKernelsInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonTMFermionInstantiation.cc.master
|
||||
@@ -1 +0,0 @@
|
||||
#define IMPLEMENTATION lexWilsonImplD
|
||||
-1
@@ -1 +0,0 @@
|
||||
../CayleyFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../ContinuedFractionFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../DomainWallEOFAFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../MobiusEOFAFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../PartialFractionFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonCloverFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonFermion5DInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonFermionInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonKernelsInstantiation.cc.master
|
||||
-1
@@ -1 +0,0 @@
|
||||
../WilsonTMFermionInstantiation.cc.master
|
||||
@@ -1 +0,0 @@
|
||||
#define IMPLEMENTATION lexWilsonImplF
|
||||
@@ -60,10 +60,8 @@ NAMESPACE_BEGIN(Grid);
|
||||
typedef typename Impl::SiteField SiteField; \
|
||||
typedef typename Impl::Field Field;
|
||||
|
||||
// Order of the exponential approximation
|
||||
const int NexpDefault = 12;
|
||||
|
||||
template <class S, int Nrepresentation = Nc, int Nexp = NexpDefault, class Group = SU<Nc> > class GaugeImplTypes {
|
||||
// hardcodes the exponential approximation in the template
|
||||
template <class S, int Nrepresentation = Nc, int Nexp = 12, class Group = SU<Nc> > class GaugeImplTypes {
|
||||
public:
|
||||
typedef S Simd;
|
||||
typedef typename Simd::scalar_type scalar_type;
|
||||
@@ -190,29 +188,14 @@ typedef GaugeImplTypes<vComplex, Nc> GimplTypesR;
|
||||
typedef GaugeImplTypes<vComplexF, Nc> GimplTypesF;
|
||||
typedef GaugeImplTypes<vComplexD, Nc> GimplTypesD;
|
||||
|
||||
typedef GaugeImplTypes<vComplex, Nc, NexpDefault, Sp<Nc> > SpGimplTypesR;
|
||||
typedef GaugeImplTypes<vComplexF, Nc, NexpDefault, Sp<Nc> > SpGimplTypesF;
|
||||
typedef GaugeImplTypes<vComplexD, Nc, NexpDefault, Sp<Nc> > SpGimplTypesD;
|
||||
typedef GaugeImplTypes<vComplex, Nc, 12, Sp<Nc> > SpGimplTypesR;
|
||||
typedef GaugeImplTypes<vComplexF, Nc, 12, Sp<Nc> > SpGimplTypesF;
|
||||
typedef GaugeImplTypes<vComplexD, Nc, 12, Sp<Nc> > SpGimplTypesD;
|
||||
|
||||
typedef GaugeImplTypes<vComplex, SU<Nc>::AdjointDimension> GimplAdjointTypesR;
|
||||
typedef GaugeImplTypes<vComplexF, SU<Nc>::AdjointDimension> GimplAdjointTypesF;
|
||||
typedef GaugeImplTypes<vComplexD, SU<Nc>::AdjointDimension> GimplAdjointTypesD;
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// Lexicographic gauge implementation types
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
typedef GaugeImplTypes<sComplexF, Nc> lexGimplTypesF;
|
||||
typedef GaugeImplTypes<sComplexD, Nc> lexGimplTypesD;
|
||||
|
||||
typedef GaugeImplTypes<sComplexF, Nc, NexpDefault, Sp<Nc> > lexSpGimplTypesF;
|
||||
typedef GaugeImplTypes<sComplexD, Nc, NexpDefault, Sp<Nc> > lexSpGimplTypesD;
|
||||
|
||||
typedef GaugeImplTypes<sComplexF, SU<Nc>::AdjointDimension> lexGimplAdjointTypesF;
|
||||
typedef GaugeImplTypes<sComplexD, SU<Nc>::AdjointDimension> lexGimplAdjointTypesD;
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// End lexicographic gauge implementation types
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -197,24 +197,6 @@ typedef PeriodicGaugeImpl<SpGimplTypesR> SpPeriodicGimplR; // Real.. whichever p
|
||||
typedef PeriodicGaugeImpl<SpGimplTypesF> SpPeriodicGimplF; // Float
|
||||
typedef PeriodicGaugeImpl<SpGimplTypesD> SpPeriodicGimplD; // Double
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// Lexicographic gauge implementations
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
typedef PeriodicGaugeImpl<lexGimplTypesF> lexPeriodicGimplF;
|
||||
typedef PeriodicGaugeImpl<lexGimplTypesD> lexPeriodicGimplD;
|
||||
|
||||
typedef PeriodicGaugeImpl<lexGimplAdjointTypesF> lexPeriodicGimplAdjF;
|
||||
typedef PeriodicGaugeImpl<lexGimplAdjointTypesD> lexPeriodicGimplAdjD;
|
||||
|
||||
typedef ConjugateGaugeImpl<lexGimplTypesF> lexConjugateGimplF;
|
||||
typedef ConjugateGaugeImpl<lexGimplTypesD> lexConjugateGimplD;
|
||||
|
||||
typedef PeriodicGaugeImpl<lexSpGimplTypesF> lexSpPeriodicGimplF;
|
||||
typedef PeriodicGaugeImpl<lexSpGimplTypesD> lexSpPeriodicGimplD;
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// End lexicographic gauge implementations
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/qcd/action/pseudofermion/TwoFlavourBosonPseudoFermion.h
|
||||
|
||||
Copyright (C) 2026
|
||||
|
||||
Author: Peter Boyle <pboyle@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#pragma once
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Two flavour BOSON (wrong-sign) pseudofermion for any FermionOperator B:
|
||||
//
|
||||
// S2 = chi^dag Bdag B chi = |B chi|^2
|
||||
//
|
||||
// integral ==> det( Bdag B )^-1 = |det B|^-2
|
||||
//
|
||||
// A compensator monomial: supplies an INVERSE determinant with NO solve in
|
||||
// the force or the action -- both are matrix multiplies. The only solve is
|
||||
// the heatbath chi = B^-1 eta, once per trajectory (for B = the
|
||||
// Pauli-Villars operator this is a mass-one solve, trivially cheap).
|
||||
//
|
||||
// Primary use: two instances with B = PV cancel the |det PV|^2 excess of
|
||||
// TwoFlavourPVdagMPseudoFermionAction down to the DWF quotient
|
||||
// |det M|^2/|det PV|^2 (two unsquared instances rather than one squared
|
||||
// kernel: first powers of PV in the force, milder). Being generic in B it
|
||||
// also serves Hasenbusch-chain compensation at intermediate masses, or any
|
||||
// future inverse-det bookkeeping. (Sibling of the domain-decomposed boson
|
||||
// in DomainDecomposedBoundaryTwoFlavourBosonPseudoFermion.h, without the
|
||||
// boundary machinery.)
|
||||
//
|
||||
// Heatbath exact by construction: S2 after refresh = |B B^-1 eta|^2 = |eta|^2.
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
template<class Impl>
|
||||
class TwoFlavourBosonPseudoFermionAction : public Action<typename Impl::GaugeField> {
|
||||
public:
|
||||
INHERIT_IMPL_TYPES(Impl);
|
||||
|
||||
private:
|
||||
FermionOperator<Impl> & BOp; // the operator whose |det|^-2 is supplied
|
||||
|
||||
LinearFunction<FermionField> &HeatbathSolver; // b -> B^-1 b (heatbath only)
|
||||
|
||||
FermionField Chi; // the pseudo fermion field for this trajectory
|
||||
|
||||
public:
|
||||
TwoFlavourBosonPseudoFermionAction(FermionOperator<Impl> &_BOp,
|
||||
LinearFunction<FermionField> & HS
|
||||
) : BOp(_BOp),
|
||||
HeatbathSolver(HS),
|
||||
Chi(_BOp.FermionGrid())
|
||||
{};
|
||||
|
||||
virtual std::string action_name(){return "TwoFlavourBosonPseudoFermionAction";}
|
||||
|
||||
virtual std::string LogParameters(){
|
||||
std::stringstream sstream;
|
||||
sstream << GridLogMessage << "["<<action_name()<<"] has no parameters" << std::endl;
|
||||
return sstream.str();
|
||||
}
|
||||
|
||||
virtual void refresh(const GaugeField &U, GridSerialRNG &sRNG, GridParallelRNG& pRNG) {
|
||||
// P(chi) = e^{- chi^dag BdagB chi} ; chi = B^-1 eta ; P(eta) = e^{-eta^dag eta}
|
||||
// e^{-x^2/2 sig^2} => sig^2 = 0.5 ; eta enters with width 1/sqrt(2).
|
||||
RealD scale = std::sqrt(0.5);
|
||||
FermionField eta(BOp.FermionGrid());
|
||||
gaussian(pRNG,eta);
|
||||
eta = eta * scale;
|
||||
refresh(U,eta);
|
||||
}
|
||||
|
||||
// Deterministic-noise variant (test hook):
|
||||
// after this, S(U) == norm2(eta) exactly (to solver tolerance).
|
||||
void refresh(const GaugeField &U, const FermionField &eta) {
|
||||
BOp.ImportGauge(U);
|
||||
Chi = Zero();
|
||||
HeatbathSolver(eta,Chi); // Chi = B^-1 eta : the ONLY solve
|
||||
std::cout << GridLogMessage << action_name() << " refresh |Chi|^2 = "<< norm2(Chi)<<std::endl;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
// S2 = |B chi|^2 -- matrix multiply only
|
||||
//////////////////////////////////////////////////////
|
||||
virtual RealD S(const GaugeField &U) {
|
||||
BOp.ImportGauge(U);
|
||||
|
||||
FermionField w(BOp.FermionGrid());
|
||||
BOp.M(Chi,w); // w = B chi
|
||||
RealD action = norm2(w);
|
||||
return action;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
// dS2 = chi^dag dBdag w + w^dag dB chi , w = B chi
|
||||
// NO solves.
|
||||
//////////////////////////////////////////////////////
|
||||
virtual void deriv(const GaugeField &U,GaugeField & dSdU) {
|
||||
BOp.ImportGauge(U);
|
||||
|
||||
FermionField w(BOp.FermionGrid());
|
||||
GaugeField force(BOp.GaugeGrid());
|
||||
|
||||
BOp.M(Chi,w); // w = B chi
|
||||
|
||||
BOp.MDeriv(force, Chi, w, DaggerYes); dSdU = force;
|
||||
BOp.MDeriv(force, w, Chi, DaggerNo ); dSdU = dSdU+force;
|
||||
|
||||
dSdU *= -1.0; // Grid action sign convention (cf TwoFlavourRatio.h)
|
||||
};
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -1,183 +0,0 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/qcd/action/pseudofermion/TwoFlavourPVdagMPseudoFermion.h
|
||||
|
||||
Copyright (C) 2026
|
||||
|
||||
Author: Peter Boyle <pboyle@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#pragma once
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Two flavour pseudofermion on the COMPOSITE operator F = PVdag M :
|
||||
//
|
||||
// S1 = phi^dag (Fdag F)^-1 phi
|
||||
//
|
||||
// integral ==> det( Mdag PV PVdag M ) = |det M|^2 |det PV|^2
|
||||
//
|
||||
// i.e. the target two-flavour |det M|^2 TIMES an excess |det PV|^2, to be
|
||||
// cancelled by compensator monomials (two TwoFlavourBosonPseudoFermionAction
|
||||
// instances on PV, each contributing |det PV|^-2, net |det PV|^-4; together
|
||||
// with this action's |det PV|^2 the ensemble carries |det M|^2/|det PV|^2 --
|
||||
// the standard DWF quotient).
|
||||
//
|
||||
// Why this shape: F = PVdag M is exactly the operator the non-Hermitian
|
||||
// multigrid coarsens, so its cycles precondition (Fdag F) natively. The
|
||||
// outer solve is CG on a Hermitian positive definite system -- the
|
||||
// non-normality is quarantined inside the preconditioner. One solve per
|
||||
// force evaluation; all other force ingredients are matrix multiplies.
|
||||
//
|
||||
// Heatbath is exact by OPERATOR ALGEBRA (no wall/projection identity):
|
||||
// refresh: phi = Fdag eta ==> S1 = eta^dag F (Fdag F)^-1 Fdag eta
|
||||
// = |eta|^2 (to solver tol)
|
||||
//
|
||||
// Hasenbusch: nothing here requires PVOp to have mass one. Any
|
||||
// (heavier,lighter) pair F(m1,m2) = D^dag(m1) D(m2) works, each rung
|
||||
// coarsenable by the same machinery; compensate intermediate-mass excess
|
||||
// dets with boson monomials on the heavier operator.
|
||||
//
|
||||
// Solver slots map b -> (Fdag F)^-1 b (full grid, zero guess imposed
|
||||
// internally). The class is agnostic to the implementation: plain CG on
|
||||
// the normal equations for testing; sequential MG solves of Fdag and F, or
|
||||
// preconditioned CG with a frozen-cycle G Gdag preconditioner in production.
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
template<class Impl>
|
||||
class TwoFlavourPVdagMPseudoFermionAction : public Action<typename Impl::GaugeField> {
|
||||
public:
|
||||
INHERIT_IMPL_TYPES(Impl);
|
||||
|
||||
private:
|
||||
FermionOperator<Impl> & PVOp; // the heavier / Pauli-Villars operator
|
||||
FermionOperator<Impl> & MOp; // the lighter operator
|
||||
|
||||
LinearFunction<FermionField> &DerivSolver; // b -> (FdagF)^-1 b, MD tolerance
|
||||
LinearFunction<FermionField> &ActionSolver; // b -> (FdagF)^-1 b, accept/reject tolerance
|
||||
|
||||
FermionField Phi; // the pseudo fermion field for this trajectory
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// F = PVdag M and Fdag = Mdag PV
|
||||
////////////////////////////////////////////////////////////////////
|
||||
void Fapply(const FermionField &in, FermionField &out) {
|
||||
FermionField tmp(MOp.FermionGrid());
|
||||
MOp.M(in,tmp);
|
||||
PVOp.Mdag(tmp,out);
|
||||
}
|
||||
void FdagApply(const FermionField &in, FermionField &out) {
|
||||
FermionField tmp(MOp.FermionGrid());
|
||||
PVOp.M(in,tmp);
|
||||
MOp.Mdag(tmp,out);
|
||||
}
|
||||
|
||||
public:
|
||||
TwoFlavourPVdagMPseudoFermionAction(FermionOperator<Impl> &_PVOp,
|
||||
FermionOperator<Impl> &_MOp,
|
||||
LinearFunction<FermionField> & DS,
|
||||
LinearFunction<FermionField> & AS
|
||||
) : PVOp(_PVOp),
|
||||
MOp(_MOp),
|
||||
DerivSolver(DS),
|
||||
ActionSolver(AS),
|
||||
Phi(_MOp.FermionGrid())
|
||||
{};
|
||||
|
||||
virtual std::string action_name(){return "TwoFlavourPVdagMPseudoFermionAction";}
|
||||
|
||||
virtual std::string LogParameters(){
|
||||
std::stringstream sstream;
|
||||
sstream << GridLogMessage << "["<<action_name()<<"] has no parameters" << std::endl;
|
||||
return sstream.str();
|
||||
}
|
||||
|
||||
virtual void refresh(const GaugeField &U, GridSerialRNG &sRNG, GridParallelRNG& pRNG) {
|
||||
// P(phi) = e^{- phi^dag (FdagF)^-1 phi} ; phi = Fdag eta ; P(eta) = e^{-eta^dag eta}
|
||||
// e^{-x^2/2 sig^2} => sig^2 = 0.5 ; eta enters with width 1/sqrt(2).
|
||||
RealD scale = std::sqrt(0.5);
|
||||
FermionField eta(MOp.FermionGrid());
|
||||
gaussian(pRNG,eta);
|
||||
eta = eta * scale;
|
||||
refresh(U,eta);
|
||||
}
|
||||
|
||||
// Deterministic-noise variant (test hook, TwoFlavourEvenOddRatio idiom):
|
||||
// after this, S(U) == norm2(eta) exactly (to solver tolerance).
|
||||
void refresh(const GaugeField &U, const FermionField &eta) {
|
||||
PVOp.ImportGauge(U);
|
||||
MOp.ImportGauge(U);
|
||||
FdagApply(eta,Phi); // NO solve: heatbath is two matmuls
|
||||
std::cout << GridLogMessage << action_name() << " refresh |Phi|^2 = "<< norm2(Phi)<<std::endl;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
// S1 = phi^dag (FdagF)^-1 phi
|
||||
//////////////////////////////////////////////////////
|
||||
virtual RealD S(const GaugeField &U) {
|
||||
PVOp.ImportGauge(U);
|
||||
MOp.ImportGauge(U);
|
||||
|
||||
FermionField X(MOp.FermionGrid());
|
||||
X = Zero();
|
||||
ActionSolver(Phi,X); // X = (FdagF)^-1 phi
|
||||
|
||||
RealD action = real(innerProduct(Phi,X)); // Hermitian positive kernel
|
||||
return action;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
// dS1 = - X^dag [ dFdag F + Fdag dF ] X , X = (FdagF)^-1 phi, Y = F X
|
||||
//
|
||||
// dF = dPVdag M + PVdag dM ==> with A = M X, B = PV Y :
|
||||
//
|
||||
// dS1 = - X^dag dMdag B - B^dag dM X - A^dag dPV Y - Y^dag dPVdag A
|
||||
//
|
||||
// ONE solve; A,Y,B by matrix multiply (Y = PVdag A reuses A).
|
||||
//////////////////////////////////////////////////////
|
||||
virtual void deriv(const GaugeField &U,GaugeField & dSdU) {
|
||||
PVOp.ImportGauge(U);
|
||||
MOp.ImportGauge(U);
|
||||
|
||||
FermionField X(MOp.FermionGrid());
|
||||
FermionField Y(MOp.FermionGrid());
|
||||
FermionField A(MOp.FermionGrid());
|
||||
FermionField B(MOp.FermionGrid());
|
||||
|
||||
GaugeField force(MOp.GaugeGrid());
|
||||
|
||||
X = Zero();
|
||||
DerivSolver(Phi,X); // X = (FdagF)^-1 phi
|
||||
MOp.M(X,A); // A = M X
|
||||
PVOp.Mdag(A,Y); // Y = PVdag A = F X
|
||||
PVOp.M(Y,B); // B = PV Y
|
||||
|
||||
// dS1 = -( X^dag dMdag B + B^dag dM X + A^dag dPV Y + Y^dag dPVdag A )
|
||||
MOp.MDeriv (force, X, B, DaggerYes); dSdU = -force;
|
||||
MOp.MDeriv (force, B, X, DaggerNo ); dSdU = dSdU -force;
|
||||
PVOp.MDeriv(force, A, Y, DaggerNo ); dSdU = dSdU -force;
|
||||
PVOp.MDeriv(force, Y, A, DaggerYes); dSdU = dSdU -force;
|
||||
|
||||
dSdU *= -1.0; // Grid action sign convention (cf TwoFlavourRatio.h)
|
||||
};
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
@@ -1,264 +0,0 @@
|
||||
/*************************************************************************************
|
||||
|
||||
Grid physics library, www.github.com/paboyle/Grid
|
||||
|
||||
Source file: ./lib/qcd/action/pseudofermion/TwoFlavourRatio4DPseudoFermion.h
|
||||
|
||||
Copyright (C) 2026
|
||||
|
||||
Author: Peter Boyle <pboyle@bnl.gov>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
See the full license in the file "LICENSE" in the top level distribution directory
|
||||
*************************************************************************************/
|
||||
/* END LEGAL */
|
||||
#pragma once
|
||||
|
||||
NAMESPACE_BEGIN(Grid);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Two flavour ratio with FOUR dimensional pseudofermion, UNpreconditioned
|
||||
// (full grid) solves.
|
||||
//
|
||||
// Companion to TwoFlavourRatioEO4DPseudoFermion.h but with the solver
|
||||
// plumbing exposed as LinearFunction<FermionField> objects that already
|
||||
// know their operator -- the natural interface for the non-Hermitian
|
||||
// multigrid GCR stack (PVdagM), which solves M and Mdag DIRECTLY rather
|
||||
// than through SchurRedBlack normal equations.
|
||||
//
|
||||
// Why: with 5D pseudofermions the squared-operator formulation hands
|
||||
// normal-equation solvers (MdagM)^-1 phi AND Mdag^-1 phi from ONE Krylov
|
||||
// space; a direct solver must solve twice, halving its per-solve gain.
|
||||
// The 4D pseudofermion action needs one M^-1 and one M^-dag solve per
|
||||
// force evaluation FOR BOTH solver families, so the direct-solver gain
|
||||
// carries through undiluted. In addition phi4 is Ls-agnostic, so the
|
||||
// force can be evaluated with a reduced-Ls operator pair while the
|
||||
// accept/reject uses full Ls (inexact force, exact action).
|
||||
//
|
||||
// Solver slots (all full-grid 5D LinearFunctions, solution overwritten,
|
||||
// zero guess imposed internally):
|
||||
// DerivMinvSolver : x = M^-1 b (DenOp)
|
||||
// DerivMdagInvSolver : x = M^-dag b (DenOp). For G5R5-hermitian
|
||||
// actions this may be implemented by the caller as
|
||||
// G5R5 . DerivMinvSolver . G5R5 -- no adjoint
|
||||
// multigrid needed.
|
||||
// ActionMinvSolver : x = M^-1 b (DenOp, accept/reject tolerance)
|
||||
// HeatbathVinvSolver : x = V^-1 b (NumOp)
|
||||
//
|
||||
// 4D <-> 5D wall maps: the action is S = | P (M^-1 V) Pdag phi4 |^2 where
|
||||
// (P,Pdag) MUST be a mutually adjoint pair for S and deriv to be
|
||||
// consistent. Two candidate conventions, selected by solution_walls:
|
||||
// true : P = P_- psi(0) + P_+ psi(Ls-1) (solution walls, matches
|
||||
// ExportPhysicalFermionSolution) and Pdag its literal adjoint.
|
||||
// false : P = P_+ psi(0) + P_- psi(Ls-1) (source walls, Pdag matches
|
||||
// ImportUnphysicalFermion).
|
||||
// The heatbath is exact iff [P M^-1 V Pdag][P V^-1 M Pdag] = 1 (the 4D
|
||||
// effective-operator composition identity); which convention satisfies it
|
||||
// is settled numerically by the refresh test S == 0.5*|eta4|^2 exactly.
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
template<class Impl>
|
||||
class TwoFlavourRatio4DPseudoFermionAction : public Action<typename Impl::GaugeField> {
|
||||
public:
|
||||
INHERIT_IMPL_TYPES(Impl);
|
||||
|
||||
private:
|
||||
typedef FermionOperator<Impl> FermOp;
|
||||
FermionOperator<Impl> & NumOp;// the basic operator (V)
|
||||
FermionOperator<Impl> & DenOp;// the basic operator (M)
|
||||
|
||||
LinearFunction<FermionField> &DerivMinvSolver;
|
||||
LinearFunction<FermionField> &DerivMdagInvSolver;
|
||||
LinearFunction<FermionField> &ActionMinvSolver;
|
||||
LinearFunction<FermionField> &HeatbathVinvSolver;
|
||||
|
||||
FermionField phi4; // the pseudo fermion field for this trajectory
|
||||
|
||||
int solution_walls; // wall convention for the (P,Pdag) pair; see header
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// The mutually adjoint 4D <-> 5D pair.
|
||||
// Wall4D : q4 = P psi5 (extract)
|
||||
// Wall4DAdj : psi5 = Pdag q4 (insert; literal adjoint of Wall4D)
|
||||
////////////////////////////////////////////////////////////////////
|
||||
void Wall4D(const FermionField &psi5, FermionField &q4)
|
||||
{
|
||||
int Ls = NumOp.FermionGrid()->_fdimensions[0];
|
||||
FermionField tmp(NumOp.FermionGrid());
|
||||
if ( solution_walls ) {
|
||||
// q4 = P_- psi(0) + P_+ psi(Ls-1)
|
||||
axpby_ssp_pminus(tmp, 0., psi5, 1., psi5, 0, 0);
|
||||
axpby_ssp_pplus (tmp, 1., tmp , 1., psi5, 0, Ls-1);
|
||||
} else {
|
||||
// q4 = P_+ psi(0) + P_- psi(Ls-1)
|
||||
axpby_ssp_pplus (tmp, 0., psi5, 1., psi5, 0, 0);
|
||||
axpby_ssp_pminus(tmp, 1., tmp , 1., psi5, 0, Ls-1);
|
||||
}
|
||||
ExtractSlice(q4, tmp, 0, 0);
|
||||
}
|
||||
void Wall4DAdj(const FermionField &q4, FermionField &psi5)
|
||||
{
|
||||
int Ls = NumOp.FermionGrid()->_fdimensions[0];
|
||||
FermionField tmp(NumOp.FermionGrid());
|
||||
tmp = Zero();
|
||||
InsertSlice(q4, tmp, 0 , 0);
|
||||
InsertSlice(q4, tmp, Ls-1, 0);
|
||||
if ( solution_walls ) {
|
||||
// psi(0) = P_- q4 ; psi(Ls-1) = P_+ q4
|
||||
axpby_ssp_pminus(tmp, 0., tmp, 1., tmp, 0 , 0);
|
||||
axpby_ssp_pplus (tmp, 0., tmp, 1., tmp, Ls-1, Ls-1);
|
||||
} else {
|
||||
// psi(0) = P_+ q4 ; psi(Ls-1) = P_- q4
|
||||
axpby_ssp_pplus (tmp, 0., tmp, 1., tmp, 0 , 0);
|
||||
axpby_ssp_pminus(tmp, 0., tmp, 1., tmp, Ls-1, Ls-1);
|
||||
}
|
||||
psi5 = tmp;
|
||||
}
|
||||
|
||||
public:
|
||||
TwoFlavourRatio4DPseudoFermionAction(FermionOperator<Impl> &_NumOp,
|
||||
FermionOperator<Impl> &_DenOp,
|
||||
LinearFunction<FermionField> & DMS,
|
||||
LinearFunction<FermionField> & DMDS,
|
||||
LinearFunction<FermionField> & AMS,
|
||||
LinearFunction<FermionField> & HVS,
|
||||
int _solution_walls = 1
|
||||
) : NumOp(_NumOp),
|
||||
DenOp(_DenOp),
|
||||
DerivMinvSolver(DMS),
|
||||
DerivMdagInvSolver(DMDS),
|
||||
ActionMinvSolver(AMS),
|
||||
HeatbathVinvSolver(HVS),
|
||||
phi4(_NumOp.GaugeGrid()),
|
||||
solution_walls(_solution_walls)
|
||||
{};
|
||||
|
||||
virtual std::string action_name(){return "TwoFlavourRatio4DPseudoFermionAction";}
|
||||
|
||||
virtual std::string LogParameters(){
|
||||
std::stringstream sstream;
|
||||
sstream << GridLogMessage << "["<<action_name()<<"] solution_walls " << solution_walls << std::endl;
|
||||
return sstream.str();
|
||||
}
|
||||
|
||||
virtual void refresh(const GaugeField &U, GridSerialRNG &sRNG, GridParallelRNG& pRNG) {
|
||||
|
||||
// P(phi4) = e^{- phi4^dag Beff^dag Beff phi4} ; Beff = P M^-1 V Pdag
|
||||
//
|
||||
// NumOp == V
|
||||
// DenOp == M
|
||||
//
|
||||
// Take phi4 = P V^-1 M Pdag eta4 ( = Beff^-1 eta4 by the composition
|
||||
// identity; verified numerically by S == 0.5 |eta4|^2 after refresh )
|
||||
//
|
||||
// P(eta) = e^{- eta^dag eta} ; e^{-x^2/2 sig^2} => sig^2 = 0.5
|
||||
// so eta enters with width 1/sqrt(2).
|
||||
//
|
||||
RealD scale = std::sqrt(0.5);
|
||||
|
||||
FermionField eta4(NumOp.GaugeGrid());
|
||||
FermionField eta5(NumOp.FermionGrid());
|
||||
FermionField tmp (NumOp.FermionGrid());
|
||||
FermionField phi5(NumOp.FermionGrid());
|
||||
|
||||
gaussian(pRNG,eta4);
|
||||
|
||||
NumOp.ImportGauge(U);
|
||||
DenOp.ImportGauge(U);
|
||||
|
||||
Wall4DAdj(eta4,eta5); // eta5 = Pdag eta4
|
||||
DenOp.M(eta5,tmp); // tmp = M eta5
|
||||
phi5 = Zero();
|
||||
HeatbathVinvSolver(tmp,phi5); // phi5 = V^-1 M eta5
|
||||
Wall4D(phi5,phi4); // phi4 = P phi5
|
||||
phi4 = phi4*scale;
|
||||
|
||||
std::cout << GridLogMessage << "4d pf (non-EO) refresh "<< norm2(phi4)<<"\n";
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
// S = phi4^dag (Pdag^dag V^dag M^-dag P^dag) (P M^-1 V Pdag) phi4
|
||||
// = | P M^-1 V Pdag phi4 |^2
|
||||
//////////////////////////////////////////////////////
|
||||
virtual RealD S(const GaugeField &U) {
|
||||
|
||||
NumOp.ImportGauge(U);
|
||||
DenOp.ImportGauge(U);
|
||||
|
||||
FermionField Y4 (NumOp.GaugeGrid());
|
||||
FermionField phi5(NumOp.FermionGrid());
|
||||
FermionField X (NumOp.FermionGrid());
|
||||
FermionField Y (NumOp.FermionGrid());
|
||||
|
||||
Wall4DAdj(phi4,phi5); // phi5 = Pdag phi4
|
||||
NumOp.M(phi5,X); // X = V phi5
|
||||
Y = Zero();
|
||||
ActionMinvSolver(X,Y); // Y = M^-1 V phi5
|
||||
Wall4D(Y,Y4); // Y4 = P Y
|
||||
|
||||
RealD action = norm2(Y4);
|
||||
|
||||
return action;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
// dS/du = 2 Re [ (M^-dag Pdag w4)^dag dV Pdag phi4 ]
|
||||
// - 2 Re [ (M^-dag Pdag w4)^dag dM (M^-1 V Pdag phi4) ]
|
||||
// with w4 = P M^-1 V Pdag phi4.
|
||||
// Two first-power solves: one M^-1, one M^-dag.
|
||||
//////////////////////////////////////////////////////
|
||||
virtual void deriv(const GaugeField &U,GaugeField & dSdU) {
|
||||
|
||||
NumOp.ImportGauge(U);
|
||||
DenOp.ImportGauge(U);
|
||||
|
||||
FermionField phi5 (NumOp.FermionGrid());
|
||||
FermionField Vphi (NumOp.FermionGrid());
|
||||
FermionField MinvVphi (NumOp.FermionGrid());
|
||||
FermionField w4 (NumOp.GaugeGrid());
|
||||
FermionField Y (NumOp.FermionGrid());
|
||||
FermionField MdagInvPdagW (NumOp.FermionGrid());
|
||||
|
||||
GaugeField force(NumOp.GaugeGrid());
|
||||
|
||||
Wall4DAdj(phi4,phi5); // phi5 = Pdag phi4
|
||||
NumOp.M(phi5,Vphi); // Vphi = V phi5
|
||||
MinvVphi = Zero();
|
||||
DerivMinvSolver(Vphi,MinvVphi); // MinvVphi = M^-1 V phi5
|
||||
std::cout << GridLogMessage << "4d pf (non-EO) deriv solve "<< norm2(MinvVphi)<<"\n";
|
||||
|
||||
// Project onto the physical 4D subspace and back: Y = Pdag P MinvVphi.
|
||||
// Pdag here MUST be the literal adjoint of the P used in S, else the
|
||||
// force is inconsistent with the action.
|
||||
Wall4D(MinvVphi,w4); // w4 = P MinvVphi
|
||||
Wall4DAdj(w4,Y); // Y = Pdag w4
|
||||
|
||||
MdagInvPdagW = Zero();
|
||||
DerivMdagInvSolver(Y,MdagInvPdagW); // = M^-dag Pdag w4 (adjoint solve)
|
||||
std::cout << GridLogMessage << "4d pf (non-EO) deriv solve dag "<< norm2(MdagInvPdagW)<<"\n";
|
||||
|
||||
// phi^dag (Pdag' Vdag Mdag^-1 P') (dV) Pdag phi + h.c.
|
||||
NumOp.MDeriv(force, MdagInvPdagW, phi5, DaggerNo ); dSdU=force;
|
||||
NumOp.MDeriv(force, phi5, MdagInvPdagW, DaggerYes); dSdU=dSdU+force;
|
||||
|
||||
// - phi^dag ( ... Mdag^-1 ) dM ( M^-1 V ... ) phi + h.c.
|
||||
DenOp.MDeriv(force, MdagInvPdagW, MinvVphi, DaggerNo ); dSdU=dSdU-force;
|
||||
DenOp.MDeriv(force, MinvVphi, MdagInvPdagW, DaggerYes); dSdU=dSdU-force;
|
||||
|
||||
dSdU *= -1.0;
|
||||
};
|
||||
};
|
||||
|
||||
NAMESPACE_END(Grid);
|
||||
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user