Skip to content

Add qdk_cutensornet's MPS engine: tensornet's MpsEngine on cuTensorNet - #4266

Open
Domingo Morales Lizama (domorale) wants to merge 3 commits into
domingom/cutensornet-loadingfrom
domingom/cutensornet-mps-engine
Open

Domingo Morales Lizama (domorale) wants to merge 3 commits into
domingom/cutensornet-loadingfrom
domingom/cutensornet-mps-engine

Conversation

@domorale

Copy link
Copy Markdown
Contributor

This adds the second part of the crate qdk_cutensornet: CuTensorNetEngine, tensornet's MpsEngine (#4229) on NVIDIA's cuTensorNet, over the libraries that discovery (#4265) loads, so that an MPS simulation method written against the trait runs on an NVIDIA GPU with no change to its code.

  • CuTensorNetEngine::new(&Availability) (Linux x86-64): the engine of one CUDA device, with its stream and cuTensorNet handle; EngineError::NoDevice without a GPU.
  • CuTensorNetState: one MPS, held as a cuTensorNet state and turned into an MPS only when a read needs it. Each compute is kept as the next start, so the next compute applies only the gates applied since: a shot's reads after each of its M measurements over G gates cost O(G), not O(M·G).
  • EngineError: a call refused by the contract (tensornet::checks, run before any native call, so a refused call makes none), or a native call that failed, named with its status.
  • One internal seam, NativeCalls, holds every call the engine makes to the CUDA Runtime and cuTensorNet (the session's, device memory's and the states'). It has two implementations: the libraries discovery loaded, and a CPU fake of them that enforces cuTensorNet's call order, so the engine's tests run in CI without a GPU.
  • policy.rs: the settings the engine fixes (the truncation cutoff, the restart period, the expectations' hyper-samples), each saying whether it was measured on the A100 or taken from the prototype.

A simulation method needs an engine that holds the chain, applies gates, truncates and reads probabilities. cuTensorNet does that work on a GPU, but its State API holds each state as a network (a start MPS and the operators applied to it) and turns it into an MPS only on request. The engine maps each MpsEngine method onto those phases (create, operator, compute, query, fork, restart, close); the README's table gives, method by method, the phases, how and why.

Of the 6,482 added lines, about 3,200 are the engine's source, 1,450 the CPU fake of the libraries, 1,400 tests, and 440 docs. The bindings do not change: the engine uses functions #4265 already binds. The crate gains two dependencies, tensornet and num-complex (already in the lock file); nothing outside it changes but the lock file.

Reading order

  1. README.md: the MPS engine's parts, its phases, and how each MpsEngine method is implemented, and why. The section on discovery is Add qdk_cutensornet: finding and loading cuTensorNet and the CUDA Runtime at run time #4265's.
  2. src/engine.rs: CuTensorNetEngine and CuTensorNetState, and the module's map.
  3. src/engine/device_session.rs: the device, stream and handle that the engine and its states share.
  4. src/engine/native_state.rs, with its folder: one cuTensorNet state, its computed MPS, its expectations and its scratch.
  5. src/engine/native_calls.rs, with session_calls.rs, memory_calls.rs, state_calls.rs and complex.rs: the seam, by kind of call.
  6. src/engine/native_calls/loaded_libraries.rs, with its folder: the seam on the loaded libraries, where all the engine's unsafe code is.
  7. src/engine/native_calls/fake_libraries.rs, with its folder: the CPU fake the tests run on.
  8. src/engine/error.rs and src/engine/policy.rs.
  9. docs/engine.md: the native calls of each phase, and the numerics.
  10. The tests: src/tests/engine.rs and its folder.

What CI does not run

CI's tests run the engine on the CPU fake, so the code that calls the real libraries is checked only on the A100 and by reading it:

  • unsafe: all 39 unsafe blocks are calls into the C libraries (38) or a read of a C string they return (1), all in native_calls/loaded_libraries.rs and its folder, one per native call, each with a SAFETY comment; the rest of the engine is safe Rust over NativeCalls.
  • The restart: every RESTART_PERIOD computes, a state moves to a new native state on a handle of its own, because the scratch a long-lived handle asks for grew past the A100's memory within a long shot; the cause in cuTensorNet is not known (policy.rs). CI checks on the fake that the restart happens on schedule, changes no value and releases the old state; that it keeps the scratch flat shows only on a GPU.
  • Drop: CI checks on the fake that dropping a state releases every native object. A failed release cannot be reported from Drop; a broken device makes the engine's next call fail and report it. Leaks on a real device can be checked with compute-sanitizer.

Testing

  • cargo test -p qdk_cutensornet --all-features: 108 tests and 2 doctests, plus one test that compiles only on Linux x86-64, on Rust 1.95, CI's version, without a GPU: the engine on the CPU fake (each method's phases and native calls, refusals making no native call, failures and cleanup), and discovery as in Add qdk_cutensornet: finding and loading cuTensorNet and the CUDA Runtime at run time #4265.
  • On an NVIDIA A100 80GB with Ubuntu 22.04, the engine passes tensornet's conformance kit (domingom/tensornet-conformance).
  • The multiplatform build passed on the previous commit of this branch, which differs from this one only in docs and comments.

This adds the crate `tensornet`: what a matrix-product-state library
does for a simulation method, in terms every MPS library shares, so a
method is written once for any library.

- `MpsEngine`: prepare a state within a capacity, apply a unitary on
  one or two sites, read P(One) (also given earlier values), project,
  fork, sample, take a `PauliSum`'s expectation, and report the chain
  it holds and the weight its truncations kept.
- `MpsShape` describes a chain by its extents: the capacity a method
  asks for, and the chain an engine holds.
- `Refusal` and `checks`: each refusal of the arguments, made once for
  every engine; an engine's error exposes it (`MpsEngineError`).
- `sampling::sample_by_conditionals`: an engine's `sample` from its
  conditional probabilities, written once.
- `ExactReference` (feature `conformance`): the exact engine every
  other one is checked against, for tests.
… at run time

A new crate that lets the QDK run tensor-network simulations, the MPS
simulator first, on an NVIDIA GPU through cuTensorNet without making
NVIDIA software part of the QDK's build. Most users have neither library,
so the QDK must build, install and run without them. Nothing is linked:
`discover()` opens libcudart.so.12 and libcutensornet.so.2 on the host,
looks up every function the engine calls into typed function-pointer
tables, and accepts exactly the audited versions (cuTensorNet 2.13.0, CUDA
Runtime 12.9). It returns an `Availability` that keeps both libraries
loaded with their tables (`LoadedLibraries`), or an `AvailabilityError`
that lists every fault of every library, so a caller can report it or run
on the CPU instead, and the user fixes an installation in one pass.
Discovery runs no GPU work; off Linux x86-64 it reports the platform as
unsupported.

- The report (`discovery/report.rs`) is a list with one `LibraryReport`
  per library (its name, path, `Version`s and `LibraryFault`s, in
  `libraries/report.rs`, where each library is opened and checked), so
  adding a library changes no public type. Each library has one file,
  `libraries/cutensornet.rs` and `libraries/cuda_runtime.rs`, implementing
  the internal `NativeLibrary` trait: its name, override variable, default
  paths, function table and version probe; opening a file and looking up
  its functions is `libraries/loader.rs`'s. `LoadedLibraries` is the one
  place that lists the libraries a GPU run needs, so discovery names none;
  the header of `libraries.rs` says how to bind another. Discovery takes
  the CUDA Runtime, then cuTensorNet, through the same steps (read the
  override, open, look up, read and check the versions), each library
  whatever the other's faults. Once a library is open, every missing
  function and every version fault is reported; the version functions are
  looked up on their own, so the versions are read even when other
  functions are missing.
- Each library's functions are listed once, as the rows of its table
  (cuTensorNet's 27: context, state, workspace, operator, expectation; the
  CUDA Runtime's 13: version, device, memory, stream), checked at compile
  time against the bindings. `scripts/generate_bindings.py` generates the
  bindings with bindgen from NVIDIA's headers in pinned archives: each
  library's whole API, the names with its prefix, so binding another
  function of a bound release is a table row and its type. Every input
  that can change them (archives, bindgen and its libclang, rustfmt,
  target, Rust edition) is pinned, and `--check` confirms that the
  checked-in files are reproduced.
  `scripts/generate_bindings.toml` pins the tools and archives the
  libraries share; each library pins its own inputs (header, prefix,
  output) in `bindings.toml` in its module's folder under `src/libraries/`,
  which makes the script bind it, and its bindings are in that folder's
  `generated/` (`cutensornet/generated/v2_13.rs`,
  `cuda_runtime/generated/cudart_12.rs`), which `.gitattributes` marks as
  generated. The CUDA Runtime's bindings own CUDA's stream type, which
  cuTensorNet's import. Both files are the script's output on Linux x86-64
  (cuTensorNet's 156 functions, the CUDA Runtime's 317).
- `function_table!` makes each table from rows `required field: Type =
  symbol`, and checks at compile time that each function-pointer type is
  its symbol's declaration; compile-time assertions check that the
  bindings' header declares the accepted version, and pin the layout of
  `cuDoubleComplex`.
- Unit tests, without NVIDIA's libraries, on any Unix host (on Linux
  with glibc, those that rely on glibc's loader), cover the
  override variables, missing and refused libraries, missing functions,
  failed version probes and the accepted versions, the faults reported
  together, the report's lookups, discovery's result when only some
  libraries are usable, and the CUDA Runtime table's rows; an ignored test
  discovers the real libraries.

The README shows the steps of discovery and the faults each one can find.
`CuTensorNetEngine` implements `tensornet::MpsEngine` on cuTensorNet's
State/MPS API, so an MPS simulation method written against the trait
runs on an NVIDIA GPU; `CuTensorNetEngine::new` (Linux x86-64) opens it
on an `Availability`, the libraries the loading found and checked.

- One native state per MPS (`NativeState`), computed only when a read
  needs it and captured after each compute, so a shot that reads after
  each of M measurements over G gates pays O(G), not O(M*G).
- Every refusal is `tensornet::checks`' (`EngineError::Refused`).
  `project` returns p, reusing the P(One) just read for its site; a
  projection or a condition of probability zero or less is refused;
  every read reports a non-finite value, or a nonpositive, non-finite
  or complex squared norm, as an invalid native result.
- `fork` copies the computed MPS on the device and starts a new state
  from the copy (`cutensornetStateInitializeMPS`); it never replays
  operators.
- `sample` draws through `tensornet::sampling::sample_by_conditionals`
  from the engine's conditional probabilities.
- One scratch buffer per state, attached to every workspace descriptor
  it uses and grown by attaching the larger buffer before freeing the
  smaller, so no descriptor holds freed memory. A call may take the
  larger of the free memory and the held scratch; a growth must fit in
  the free memory alone.
- Copies run on CUDA's legacy stream, which the engine's non-blocking
  stream does not wait for: the engine synchronizes it before each
  compute and expectation, and once after a fork's copies.
- Fixed settings (`engine/policy.rs`): a discarded-weight cutoff of
  1e-14, GESVD, the simple-update gauge, device 0, 8 hyper-samples for
  each expectation's contraction path, and a restart every 10 computes
  on a cuTensorNet handle of its own, which kept the scratch flat on
  H2.
- A lone qubit is padded with an idle site cuTensorNet needs and the
  caller never sees.
- The engine and its states share an `Rc<DeviceSession>`; the native
  calls are traits (`StateCalls`, `MemoryCalls`, `SessionCalls`, their
  union `NativeCalls`, in `src/engine/native_calls.rs`), so CI runs the
  engine's real code against fake libraries on the CPU
  (`src/engine/native_calls/fake_libraries/`, one file per trait,
  compiled for the tests only) that enforce cuTensorNet's call order and
  compute with a state vector; the tests live in `src/tests/engine.rs`
  and `src/tests/engine/`.
- Every cleanup attempts each release and returns the first failure
  (`first_failure`), so a failed release leaks nothing but its own
  object.
- Dropping a state releases its device memory and native objects, all
  the contract asks. A failed release is not returned: `Drop` cannot
  return it, and a caller could not act on it. A broken device fails the
  engine's next call, which reports it; any other failure is a fault in
  the engine's call order, which the tests check against the fake
  libraries.
  Debug builds write it to stderr.

The native calls are implemented on the loaded libraries in
`src/engine/native_calls/loaded_libraries/`, one file per trait, beside
the fake libraries, so the engine depends on the libraries and not the
reverse.
Outside the engine: the legacy stream's value
(`cuda_runtime::STREAM_LEGACY`, a casting macro bindgen does not
translate), the function tables' dead-code expectations narrowed to the
version rows (read through the version tables) and the one function only
the setup check reads (`cudaDeviceGetAttribute`), the crate doc
presenting both halves, and the README, which now leads with the
engine and then the loading, with a Platforms row for the GPU.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant