Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Tensornet backends] Make controlled rank a configurable setting #2446

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions docs/sphinx/using/backends/simulators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -417,17 +417,14 @@ Specific aspects of the simulation can be configured by setting the following of
* **`CUDA_VISIBLE_DEVICES=X`**: Makes the process only see GPU X on multi-GPU nodes. Each MPI process must only see its own dedicated GPU. For example, if you run 8 MPI processes on a DGX system with 8 GPUs, each MPI process should be assigned its own dedicated GPU via `CUDA_VISIBLE_DEVICES` when invoking `mpiexec` (or `mpirun`) commands.
* **`OMP_PLACES=cores`**: Set this environment variable to improve CPU parallelization.
* **`OMP_NUM_THREADS=X`**: To enable CPU parallelization, set X to `NUMBER_OF_CORES_PER_NODE/NUMBER_OF_GPUS_PER_NODE`.
* **`CUDAQ_TENSORNET_CONTROLLED_RANK=X`**: Specify the number of controlled qubits whereby the full tensor body of the controlled gate is expanded. If the number of controlled qubits is greater than this value, the gate is applied as a controlled tensor operator to the tensor network state. Default value is 1.

.. note::

This backend requires an NVIDIA GPU and CUDA runtime libraries.
If you do not have these dependencies installed, you may encounter an error stating `Invalid simulator requested`.
See the section :ref:`dependencies-and-compatibility` for more information about how to install dependencies.

.. note::

Setting random seed, via :code:`cudaq::set_random_seed`, is not supported for this backend due to a limitation of the :code:`cuTensorNet` library. This will be fixed in future release once this feature becomes available.


Matrix product state
+++++++++++++++++++++++++++++++++++
Expand Down Expand Up @@ -471,10 +468,6 @@ Specific aspects of the simulation can be configured by defining the following e
If you do not have these dependencies installed, you may encounter an error stating `Invalid simulator requested`.
See the section :ref:`dependencies-and-compatibility` for more information about how to install dependencies.

.. note::

Setting random seed, via :code:`cudaq::set_random_seed`, is not supported for this backend due to a limitation of the :code:`cuTensorNet` library. This will be fixed in future release once this feature becomes available.

.. note::
The parallelism of Jacobi method (the default `CUDAQ_MPS_SVD_ALGO` setting) gives GPU better performance on small and medium size matrices.
If you expect a large number of singular values (e.g., increasing the `CUDAQ_MPS_MAX_BOND` setting), please adjust the `CUDAQ_MPS_SVD_ALGO` setting accordingly.
Expand Down
46 changes: 37 additions & 9 deletions runtime/nvqir/cutensornet/simulator_cutensornet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,45 @@ void SimulatorTensorNetBase::applyGate(const GateApplicationTask &task) {
}
return paramsSs.str() + "__" + std::to_string(vecComplexHash(task.matrix));
}();
const auto iter = m_gateDeviceMemCache.find(gateKey);

// This is the first time we see this gate, allocate device mem and cache it.
if (iter == m_gateDeviceMemCache.end()) {
void *dMem = allocateGateMatrix(task.matrix);
m_gateDeviceMemCache[gateKey] = dMem;
if (controls.size() <= m_maxControlledRankForFullTensorExpansion) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a test to cover this scenario?

// If the number of controlled qubits is less than the threshold, expand the
// full matrix and apply it as a single tensor operation.
// Qubit operands are now both control and target qubits.
std::vector<std::int32_t> qubitOperands(controls.begin(), controls.end());
qubitOperands.insert(qubitOperands.end(), targets.begin(), targets.end());
// Use a different key for expanded gate matrix (reflecting the number of
// control qubits)
const auto expandedMatKey =
gateKey + "_c(" + std::to_string(controls.size()) + ")";
const auto iter = m_gateDeviceMemCache.find(expandedMatKey);
if (iter != m_gateDeviceMemCache.end()) {
m_state->applyGate(/*controlQubits=*/{}, qubitOperands, iter->second);
} else {
// If this is the first time seeing this (gate + number of control qubits)
// compo, compute the expanded matrix.
const auto expandedGateMat =
generateFullGateTensor(controls.size(), task.matrix);
void *dMem = allocateGateMatrix(expandedGateMat);
m_gateDeviceMemCache[expandedMatKey] = dMem;
m_state->applyGate(/*controlQubits=*/{}, qubitOperands, dMem);
}
} else {
// Propagates control qubits to cutensornet.
const auto iter = m_gateDeviceMemCache.find(gateKey);
// This is the first time we see this gate, allocate device mem and cache
// it.
if (iter == m_gateDeviceMemCache.end()) {
void *dMem = allocateGateMatrix(task.matrix);
m_gateDeviceMemCache[gateKey] = dMem;
}
// Type conversion
const std::vector<std::int32_t> ctrlQubits(controls.begin(),
controls.end());
const std::vector<std::int32_t> targetQubits(targets.begin(),
targets.end());
m_state->applyGate(ctrlQubits, targetQubits, m_gateDeviceMemCache[gateKey]);
}
// Type conversion
const std::vector<std::int32_t> ctrlQubits(controls.begin(), controls.end());
const std::vector<std::int32_t> targetQubits(targets.begin(), targets.end());
m_state->applyGate(ctrlQubits, targetQubits, m_gateDeviceMemCache[gateKey]);
}

/// @brief Reset the state of a given qubit to zero
Expand Down
7 changes: 7 additions & 0 deletions runtime/nvqir/cutensornet/simulator_cutensornet.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,13 @@ class SimulatorTensorNetBase : public nvqir::CircuitSimulatorBase<double> {
// Random number generator for generating 32-bit numbers with a state size of
// 19937 bits for measurements.
std::mt19937 m_randomEngine;
// Max number of controlled ranks (qubits) that the full matrix of the
// controlled gate is used as tensor op.
// Default is 1.
// MPS only supports 1 (higher number of controlled ranks must use
// cutensornetStateApplyControlledTensorOperator). Tensornet supports
// arbitrary values.
std::size_t m_maxControlledRankForFullTensorExpansion = 1;
};

} // end namespace nvqir
18 changes: 18 additions & 0 deletions runtime/nvqir/cutensornet/simulator_tensornet_register.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,25 @@ class SimulatorTensorNet : public SimulatorTensorNetBase {
initCuTensornetComm(m_cutnHandle);
m_cutnMpiInitialized = true;
}

// Retrieve user-defined controlled rank setting if provided.
if (auto *maxControlledRankEnvVar =
std::getenv("CUDAQ_TENSORNET_CONTROLLED_RANK")) {
auto maxControlledRank = std::atoi(maxControlledRankEnvVar);
if (maxControlledRank <= 0)
throw std::runtime_error(
fmt::format("Invalid CUDAQ_TENSORNET_CONTROLLED_RANK environment "
"variable setting. Expecting a "
"positive integer value, got '{}'.",
maxControlledRank));

cudaq::info("Setting max controlled rank for full tensor expansion from "
"{} to {}.",
m_maxControlledRankForFullTensorExpansion, maxControlledRank);
m_maxControlledRankForFullTensorExpansion = maxControlledRank;
}
}

// Nothing to do for state preparation
virtual void prepareQubitTensorState() override {}
virtual std::string name() const override { return "tensornet"; }
Expand Down
3 changes: 2 additions & 1 deletion runtime/nvqir/cutensornet/tensornet_state.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ std::unique_ptr<TensorNetState> TensorNetState::clone() const {
void TensorNetState::applyGate(const std::vector<int32_t> &controlQubits,
const std::vector<int32_t> &targetQubits,
void *gateDeviceMem, bool adjoint) {
LOG_API_TIME();
ScopedTraceWithContext("TensorNetState::applyGate", controlQubits.size(),
targetQubits.size());
if (controlQubits.empty()) {
HANDLE_CUTN_ERROR(cutensornetStateApplyTensorOperator(
m_cutnHandle, m_quantumState, targetQubits.size(), targetQubits.data(),
Expand Down
Loading