Repository navigation
Add qdk_cutensornet's MPS engine: tensornet's MpsEngine on cuTensorNet - #4266
Open
Domingo Morales Lizama (domorale) wants to merge 3 commits into
Open
Domingo Morales Lizama (domorale) wants to merge 3 commits into
Domingo Morales Lizama (domorale) wants to merge 3 commits into
Conversation
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.
Domingo Morales Lizama (domorale)
requested review from
Bill Ticehurst (billti),
Ian Davis (idavis) and
Stefan J. Wernli (swernli)
as code owners
November 12, 2026 18:35
Domingo Morales Lizama (domorale)
force-pushed
the
domingom/cutensornet-loading
branch
from
November 24, 2026 06:10
42fa6de to
4b9be79
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This adds the second part of the crate
qdk_cutensornet:CuTensorNetEngine,tensornet'sMpsEngine(#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::NoDevicewithout 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.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
MpsEnginemethod 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,
tensornetandnum-complex(already in the lock file); nothing outside it changes but the lock file.Reading order
README.md: the MPS engine's parts, its phases, and how eachMpsEnginemethod 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.src/engine.rs:CuTensorNetEngineandCuTensorNetState, and the module's map.src/engine/device_session.rs: the device, stream and handle that the engine and its states share.src/engine/native_state.rs, with its folder: one cuTensorNet state, its computed MPS, its expectations and its scratch.src/engine/native_calls.rs, withsession_calls.rs,memory_calls.rs,state_calls.rsandcomplex.rs: the seam, by kind of call.src/engine/native_calls/loaded_libraries.rs, with its folder: the seam on the loaded libraries, where all the engine'sunsafecode is.src/engine/native_calls/fake_libraries.rs, with its folder: the CPU fake the tests run on.src/engine/error.rsandsrc/engine/policy.rs.docs/engine.md: the native calls of each phase, and the numerics.src/tests/engine.rsand 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 39unsafeblocks are calls into the C libraries (38) or a read of a C string they return (1), all innative_calls/loaded_libraries.rsand its folder, one per native call, each with aSAFETYcomment; the rest of the engine is safe Rust overNativeCalls.RESTART_PERIODcomputes, 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 fromDrop; a broken device makes the engine's next call fail and report it. Leaks on a real device can be checked withcompute-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.tensornet's conformance kit (domingom/tensornet-conformance).