Skip to content

Commit

Permalink
init opt
Browse files Browse the repository at this point in the history
  • Loading branch information
dypshong committed Dec 13, 2023
1 parent 7afac77 commit b3f6c24
Show file tree
Hide file tree
Showing 18 changed files with 62 additions and 53 deletions.
49 changes: 30 additions & 19 deletions snuqs/statevector_simulator/statevector_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,29 +31,40 @@ def _run(self, circ: Circuit, ret: Dict[str, any]):
def qiskit_for_snuqs(self, circ: qiskit.QuantumCircuit):
circ = circ.copy()
new_data = []
for instr in circ.data:
if instr.operation.name == "initialize":
new_data.append(
qiskit.circuit.CircuitInstruction(
Initialize("initialize", instr.operation.num_qubits,
instr.operation.params),
instr.qubits,
instr.clbits
)
)
else:
new_data.append(instr)

circ.data = new_data
first_init = None
if circ.data[0].operation.name == "initialize" and len(circ.data[0].qubits) == circ.num_qubits:
first_init = snuqs._C.INITIALIZE(circ.data[0].operation.params)
circ.data = circ.data[1:]

# for instr in circ.data:
# if instr.operation.name == "initialize":
# new_data.append(
# qiskit.circuit.CircuitInstruction(
# Initialize("initialize", instr.operation.num_qubits,
# instr.operation.params),
# instr.qubits,
# instr.clbits
# )
# )
# else:
# new_data.append(instr)
#
# circ.data = new_data

with tempfile.NamedTemporaryFile() as f:
circ.qasm(filename=f.name)
compiler = QasmCompiler()
circ = compiler.compile(f.name)
if first_init:
circ.prepend(first_init)
return circ

def run(self, circ: Union[qiskit.QuantumCircuit, Circuit]):
if isinstance(circ, qiskit.QuantumCircuit):
circ = self.qiskit_for_snuqs(circ)
with tempfile.NamedTemporaryFile() as f:
circ.qasm(filename=f.name)
compiler = QasmCompiler()
circ = compiler.compile(f.name)

elif isinstance(circ, Circuit):
pass
else:
raise "Illegal input to simulator"
ret = {}
return Result(threading.Thread(target=self._run, args=[circ, ret]), ret)
2 changes: 1 addition & 1 deletion src/buffer/cuda_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ void CudaBuffer<T>::write(void *buf, size_t count, size_t offset) {
}

template class CudaBuffer<double>;
template class CudaBuffer<float>;
//template class CudaBuffer<float>;

} // namespace cuda
} // namespace snuqs
2 changes: 1 addition & 1 deletion src/buffer/memory_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ void MemoryBuffer<T>::__setitem__(size_t key, std::complex<T> val) {
}

template <typename T> size_t MemoryBuffer<T>::count() const { return count_; }
template class MemoryBuffer<float>;
//template class MemoryBuffer<float>;
template class MemoryBuffer<double>;

} // namespace snuqs
2 changes: 1 addition & 1 deletion src/buffer/storage_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ void StorageBuffer<T>::write(void *buf, size_t count, size_t offset) {
NOT_IMPLEMENTED();
}

template class StorageBuffer<float>;
//template class StorageBuffer<float>;
template class StorageBuffer<double>;

} // namespace snuqs
4 changes: 4 additions & 0 deletions src/circuit/circuit.cc
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ std::shared_ptr<Qreg> Circuit::getQregForIndex(size_t index) const {
}

void Circuit::append(std::shared_ptr<Qop> qop) { qops_.push_back(qop); }
void Circuit::prepend(std::shared_ptr<Qop> qop) {
qops_.insert(qops_.begin(), qop);
}

std::string Circuit::__repr__() {

std::ostringstream s;
Expand Down
1 change: 1 addition & 0 deletions src/circuit/circuit.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class Circuit {
void append_qreg(std::shared_ptr<Qreg> qreg);
void append_creg(std::shared_ptr<Creg> creg);
void append(std::shared_ptr<Qop> qop);
void prepend(std::shared_ptr<Qop> qop);

std::shared_ptr<Qreg> getQregForIndex(size_t index) const;

Expand Down
9 changes: 3 additions & 6 deletions src/circuit/qop.cc
Original file line number Diff line number Diff line change
Expand Up @@ -636,15 +636,12 @@ std::shared_ptr<Qop> CSWAP::clone() const {
return std::make_shared<CSWAP>(qargs_, params_);
}

INITIALIZE::INITIALIZE(std::vector<std::shared_ptr<Qarg>> qargs)
: Qgate(QgateType::INITIALIZE, qargs) {}
INITIALIZE::INITIALIZE(std::vector<std::shared_ptr<Qarg>> qargs,
std::vector<std::shared_ptr<Parameter>> params)
: Qgate(QgateType::INITIALIZE, qargs, params) {}
INITIALIZE::INITIALIZE(const std::vector<std::complex<double>> &params)
: Qgate(QgateType::INITIALIZE, {}, {}), init_params_(params) {}
size_t INITIALIZE::numQargs() const { return 3; }
size_t INITIALIZE::numParams() const { return 0; }
std::shared_ptr<Qop> INITIALIZE::clone() const {
return std::make_shared<INITIALIZE>(qargs_, params_);
return std::make_shared<INITIALIZE>(init_params_);
}

InitZeroState::InitZeroState() : Qop(QopType::INIT_ZERO_STATE, {}) {}
Expand Down
6 changes: 3 additions & 3 deletions src/circuit/qop.h
Original file line number Diff line number Diff line change
Expand Up @@ -526,12 +526,12 @@ class CSWAP : public Qgate {

class INITIALIZE : public Qgate {
public:
INITIALIZE(std::vector<std::shared_ptr<Qarg>> qargs);
INITIALIZE(std::vector<std::shared_ptr<Qarg>> qargs,
std::vector<std::shared_ptr<Parameter>> params);
INITIALIZE(const std::vector<std::complex<double>> &params);
virtual size_t numQargs() const override;
virtual size_t numParams() const override;
virtual std::shared_ptr<Qop> clone() const override;

std::vector<std::complex<double>> init_params_;
};

class InitZeroState : public Qop {
Expand Down
5 changes: 2 additions & 3 deletions src/module.cc
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ PYBIND11_MODULE(_C, m) {
.def("append_qreg", &snuqs::Circuit::append_qreg)
.def("append_creg", &snuqs::Circuit::append_creg)
.def("append", &snuqs::Circuit::append)
.def("prepend", &snuqs::Circuit::prepend)
.def("name", &snuqs::Circuit::name)
.def("__repr__", &snuqs::Circuit::__repr__);

Expand Down Expand Up @@ -490,9 +491,7 @@ PYBIND11_MODULE(_C, m) {

py::class_<snuqs::INITIALIZE, snuqs::Qgate,
std::shared_ptr<snuqs::INITIALIZE>>(m, "INITIALIZE")
.def(py::init<std::vector<std::shared_ptr<snuqs::Qarg>>>())
.def(py::init<std::vector<std::shared_ptr<snuqs::Qarg>>,
std::vector<std::shared_ptr<snuqs::Parameter>>>())
.def(py::init<const std::vector<std::complex<double>>&>())
.def("numQargs", &snuqs::INITIALIZE::numQargs)
.def("numParams", &snuqs::INITIALIZE::numParams);
}
7 changes: 3 additions & 4 deletions src/simulator/executor.cc
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,7 @@ static void exec_gate(Qgate *qop, Buffer<T> *buffer, size_t num_states) {
break;
case QgateType::INITIALIZE:
QopImpl<T>::initialize(buffer->ptr(), num_states,
qargsToIndices(qop->qargs_),
paramsToValues<T>(qop->params_));
reinterpret_cast<INITIALIZE *>(qop)->init_params_);
break;
default:
NOT_IMPLEMENTED();
Expand Down Expand Up @@ -256,8 +255,8 @@ void exec(Qop *qop, Buffer<T> *buffer, size_t num_states,
}
}

template void exec<float>(Qop *qop, Buffer<float> *buffer, size_t num_states,
Buffer<float> *mem_buffer);
//template void exec<float>(Qop *qop, Buffer<float> *buffer, size_t num_states,
// Buffer<float> *mem_buffer);
template void exec<double>(Qop *qop, Buffer<double> *buffer, size_t num_states,
Buffer<double> *mem_buffer);

Expand Down
8 changes: 2 additions & 6 deletions src/simulator/qop_impl.cu
Original file line number Diff line number Diff line change
Expand Up @@ -276,11 +276,7 @@ __global__ void FourQubitGate(cuda::complex<T> *buffer, size_t count,
} // namespace kernel
template <typename T>
void QopImpl<T>::initialize(std::complex<T> *buffer, size_t count,
std::vector<size_t> targets,
std::vector<std::complex<T>> params) {
if ((1ull << targets.size()) != count) {
CANNOT_BE_HERE();
}
const std::vector<std::complex<T>> &params) {
api::memcpyAsync(buffer, params.data(), sizeof(std::complex<T>) * (count),
cudaMemcpyHostToDevice, 0);
}
Expand Down Expand Up @@ -1349,8 +1345,8 @@ void QopImpl<T>::sync(std::complex<T> *buffer, size_t count,
#pragma omp barrier
}

//template class QopImpl<float>;
template class QopImpl<double>;
template class QopImpl<float>;

} // namespace cuda
} // namespace snuqs
3 changes: 1 addition & 2 deletions src/simulator/qop_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ template <typename T> class QopImpl {
static void setZero(std::complex<T> *buffer, size_t count);
static void reset(std::complex<T> *buffer, size_t count,
std::vector<size_t> targets);
static void initialize(std::complex<T> *buffer, size_t count,
std::vector<size_t> targets, std::vector<std::complex<T>> params);
static void initialize(std::complex<T> *buffer, size_t count, const std::vector<std::complex<T>> &params);

static void id(std::complex<T> *buffer, size_t count,
std::vector<size_t> targets, std::vector<std::complex<T>> params);
Expand Down
4 changes: 2 additions & 2 deletions src/simulator/run_cpu.cc
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ std::shared_ptr<Buffer<T>> runCPU(Circuit &_circ, size_t mem_per_device) {
return mem_buffer;
}

template std::shared_ptr<Buffer<float>> runCPU<float>(Circuit &circ,
size_t mem_per_device);
//template std::shared_ptr<Buffer<float>> runCPU<float>(Circuit &circ,
// size_t mem_per_device);
template std::shared_ptr<Buffer<double>> runCPU<double>(Circuit &circ,
size_t mem_per_device);
} // namespace cuda
Expand Down
2 changes: 1 addition & 1 deletion src/simulator/run_multi_gpu.cc
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ template <typename T> std::shared_ptr<Buffer<T>> runMultiGPU(Circuit &_circ) {
return mem_buffer;
}

template std::shared_ptr<Buffer<float>> runMultiGPU<float>(Circuit &circ);
//template std::shared_ptr<Buffer<float>> runMultiGPU<float>(Circuit &circ);
template std::shared_ptr<Buffer<double>> runMultiGPU<double>(Circuit &circ);
} // namespace cuda
} // namespace snuqs
2 changes: 1 addition & 1 deletion src/simulator/run_single_gpu.cc
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ template <typename T> std::shared_ptr<Buffer<T>> runSingleGPU(Circuit &_circ) {
return mem_buffer;
}

template std::shared_ptr<Buffer<float>> runSingleGPU<float>(Circuit &circ);
//template std::shared_ptr<Buffer<float>> runSingleGPU<float>(Circuit &circ);
template std::shared_ptr<Buffer<double>> runSingleGPU<double>(Circuit &circ);

} // namespace cuda
Expand Down
2 changes: 1 addition & 1 deletion src/simulator/run_storage.cc
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace cuda {
template <typename T> std::shared_ptr<Buffer<T>> runStorage(Circuit &circ) {
NOT_IMPLEMENTED();
}
template std::shared_ptr<Buffer<float>> runStorage<float>(Circuit &circ);
//template std::shared_ptr<Buffer<float>> runStorage<float>(Circuit &circ);
template std::shared_ptr<Buffer<double>> runStorage<double>(Circuit &circ);
} // namespace cuda
} // namespace snuqs
2 changes: 1 addition & 1 deletion src/simulator/statevector_simulator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ std::shared_ptr<Buffer<T>> StatevectorSimulator<T>::run(Circuit &circ) {
}
}

template class StatevectorSimulator<float>;
//template class StatevectorSimulator<float>;
template class StatevectorSimulator<double>;

} // namespace snuqs
5 changes: 4 additions & 1 deletion tests/snuqs/simulator/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def validate_parameter(self, parameter):

class BenchmarkTest(unittest.TestCase):
def test_init(self):
total_qubit = 16
total_qubit = 25
qc = QuantumCircuit(total_qubit)

np.random.seed(123)
Expand All @@ -51,9 +51,12 @@ def test_init(self):
np.random.rand(2 ** total_qubit)
init = init / np.sqrt(np.sum(np.square(np.abs(init))))
qc.initialize(init)
print("START")

state_snuqs = run_snuqs(qc)
print("A DONE")
state_qiskit = run_qiskit(qc)
print(" DONE")
phase = state_snuqs[0] / state_qiskit[0]
for x, y in zip(state_snuqs, state_qiskit):
self.assertAlmostEqual(x, y * phase)
Expand Down

0 comments on commit b3f6c24

Please sign in to comment.