Commit 32d09665 authored by Mccaskey, Alex's avatar Mccaskey, Alex
Browse files

adding c++ aer accelerator


Signed-off-by: Mccaskey, Alex's avatarAlex McCaskey <mccaskeyaj@ornl.gov>
parent 7cbaffe3
......@@ -4,8 +4,8 @@ from pelix.ipopo.decorators import ComponentFactory, Property, Requires, Provide
@ComponentFactory("aer_accelerator_factory")
@Provides("accelerator")
@Property("_accelerator", "accelerator", "aer")
@Property("_name", "name", "aer")
@Property("_accelerator", "accelerator", "aer-py")
@Property("_name", "name", "aer-py")
@Instantiate("aer_accelerator_instance")
class AerAccelerator(xacc.Accelerator):
def __init__(self):
......@@ -37,7 +37,7 @@ class AerAccelerator(xacc.Accelerator):
ro_error = True if 'readout_error' in options and options['readout_error'] else False
rel = True if 'thermal_relaxation' in options and options['thermal_relaxation'] else False
ge = True if 'gate_error' in options and options['gate_error'] else False
self.noise_model = noise.device.basic_device_noise_model(properties, readout_error=ro_error, thermal_relaxation=rel, gate_error=ge)
self.noise_model = noise.NoiseModel.from_backend(backend, readout_error=ro_error, thermal_relaxation=rel, gate_error=ge)
def updateConfiguration(self, options):
self.initialize(options)
......@@ -49,7 +49,7 @@ class AerAccelerator(xacc.Accelerator):
return self.modeled_qpu.getConnectivity()
def name(self):
return 'aer'
return 'aer-py'
def execute_one_qasm(self, buffer, program):
qobjStr = self.qobj_compiler.translate(program)
......
......@@ -10,6 +10,9 @@
# Contributors:
# Alexander J. McCaskey - initial API and implementation
# *******************************************************************************/
add_subdirectory(aer)
set(LIBRARY_NAME xacc-ibm)
set(ANTLR_LIB ${CMAKE_SOURCE_DIR}/dist/libantlr4-runtime.so)
......@@ -24,49 +27,12 @@ file(GLOB SRC
compiler/OQASMToXACCListener.cpp
compiler/generated/*.cpp)
find_package(LAPACK)
if(LAPACK_FOUND)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DLAPACK_FOUND")
message(
STATUS "${BoldGreen}Building local IBM Accelerator simulator.${ColorReset}")
list(APPEND SRC accelerator/LocalIBMAccelerator.cpp)
else()
message(
STATUS
"${BoldYellow}Could not find Blas or Lapack, skipping local IBM simulator build.${ColorReset}"
)
endif()
usfunctiongetresourcesource(TARGET ${LIBRARY_NAME} OUT SRC)
usfunctiongeneratebundleinit(TARGET ${LIBRARY_NAME} OUT SRC)
add_library(${LIBRARY_NAME} SHARED ${SRC})
if(LAPACK_FOUND)
target_include_directories(
${LIBRARY_NAME}
PUBLIC
accelerator
compiler
compiler/generated
accelerator/qiskit-terra/src/qasm-simulator-cpp/src
accelerator/qiskit-terra/src/qasm-simulator-cpp/src/backends
accelerator/qiskit-terra/src/qasm-simulator-cpp/src/engines
accelerator/qiskit-terra/src/qasm-simulator-cpp/src/utilities
accelerator/json
${CMAKE_SOURCE_DIR}/tpls/antlr/runtime/src
${CMAKE_SOURCE_DIR}/tpls/rapidjson/include)
target_link_libraries(${LIBRARY_NAME}
PUBLIC xacc
xacc-quantum-gate
${ANTLR_LIB}
CppMicroServices
${LAPACK_LIBRARIES}
PRIVATE cpr)
else()
target_include_directories(${LIBRARY_NAME}
PUBLIC accelerator
compiler
......@@ -81,7 +47,6 @@ else()
${ANTLR_LIB}
CppMicroServices PRIVATE cpr)
endif()
set(_bundle_name xacc_ibm)
set_target_properties(${LIBRARY_NAME}
......
set(LIBRARY_NAME xacc-aer)
file(GLOB SRC
accelerator/aer_accelerator.cpp)
usfunctiongetresourcesource(TARGET ${LIBRARY_NAME} OUT SRC)
usfunctiongeneratebundleinit(TARGET ${LIBRARY_NAME} OUT SRC)
add_library(${LIBRARY_NAME} SHARED ${SRC})
target_include_directories(${LIBRARY_NAME}
PUBLIC .
accelerator
src)
target_link_libraries(${LIBRARY_NAME}
PUBLIC xacc
xacc-quantum-gate
)
set(_bundle_name xacc_aer)
set_target_properties(${LIBRARY_NAME}
PROPERTIES COMPILE_DEFINITIONS
US_BUNDLE_NAME=${_bundle_name}
US_BUNDLE_NAME
${_bundle_name})
usfunctionembedresources(TARGET
${LIBRARY_NAME}
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}
FILES
manifest.json)
if(APPLE)
set_target_properties(${LIBRARY_NAME}
PROPERTIES INSTALL_RPATH "@loader_path/../lib")
set_target_properties(${LIBRARY_NAME}
PROPERTIES LINK_FLAGS "-undefined dynamic_lookup")
else()
set_target_properties(${LIBRARY_NAME}
PROPERTIES INSTALL_RPATH "$ORIGIN/../lib")
set_target_properties(${LIBRARY_NAME} PROPERTIES LINK_FLAGS "-shared")
endif()
#if(XACC_BUILD_TESTS)
add_subdirectory(tests)
#endif()
install(TARGETS ${LIBRARY_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX}/plugins)
/*******************************************************************************
* Copyright (c) 2019 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompanies this
* distribution. The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
*License is available at https://eclipse.org/org/documents/edl-v10.php
*
* Contributors:
* Thien Nguyen - initial API and implementation
*******************************************************************************/
#include "aer_accelerator.hpp"
#include "CommonGates.hpp"
#include "CountGatesOfTypeVisitor.hpp"
#include "InstructionIterator.hpp"
#include "controllers/controller.hpp"
#include "controllers/controller_execute.hpp"
#include "controllers/qasm_controller.hpp"
#include "controllers/statevector_controller.hpp"
#include "noise/readout_error.hpp"
#include "cppmicroservices/BundleActivator.h"
#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/ServiceProperties.h"
#include "xacc.hpp"
#include <bitset>
namespace xacc {
namespace quantum {
#define IS_INTEGRAL(T) \
typename std::enable_if<std::is_integral<T>::value>::type * = 0
template <class T>
std::string integral_to_binary_string(T byte, IS_INTEGRAL(T)) {
std::bitset<sizeof(T) * 8> bs(byte);
return bs.to_string();
}
std::string hex_string_to_binary_string(std::string hex) {
return integral_to_binary_string((int)strtol(hex.c_str(), NULL, 0));
}
void AerAccelerator::initialize(const HeterogeneousMap &params) {
noise_model.clear();
m_simtype = "qasm";
xacc_to_qobj = xacc::getCompiler("qobj");
if (params.keyExists<int>("shots")) {
m_shots = params.get<int>("shots");
}
if (params.stringExists("sim-type")) {
if (!xacc::container::contains(
std::vector<std::string>{"qasm", "statevector"},
params.getString("sim-type"))) {
xacc::warning("[Aer] warning, invalid sim-type (" +
params.getString("sim-type") +
"), must be qasm or statevector.");
} else {
m_simtype = params.getString("sim-type");
}
}
if (params.stringExists("backend")) {
auto ibm = xacc::getAccelerator("ibm:" + params.getString("backend"));
auto props = ibm->getProperties().get<std::string>("total-json");
auto props_json = nlohmann::json::parse(props);
// nlohmann::json errors_json;
std::vector<nlohmann::json> elements;
std::size_t qbit = 0;
for (auto it = props_json["qubits"].begin();
it != props_json["qubits"].end(); ++it) {
std::vector<double> value{(*(it->begin() + 5))["value"].get<double>(),
(*(it->begin() + 4))["value"].get<double>()};
std::vector<std::vector<double>> probs{{1 - value[0], value[0]},
{value[1], 1 - value[1]}};
nlohmann::json element;
element["type"] = "roerror";
element["operations"] = std::vector<std::string>{"measure"};
element["probabilities"] = probs;
element["gate_qubits"] = std::vector<std::vector<std::size_t>>{{qbit}};
elements.push_back(element);
qbit++;
}
noise_model["errors"] = elements;
// noise_model["x90_gates"] = std::vecto
std::cout << "NoiseModelJson:\n" << noise_model.dump(4) << "\n";
}
}
void AerAccelerator::execute(
std::shared_ptr<AcceleratorBuffer> buffer,
const std::shared_ptr<CompositeInstruction> program) {
if (m_simtype == "qasm") {
auto qobj_str = xacc_to_qobj->translate(program);
nlohmann::json j = nlohmann::json::parse(qobj_str)["qObject"];
j["config"]["shots"] = m_shots;
j["config"]["noise_model"] = noise_model;
auto results_json = nlohmann::json::parse(
AER::controller_execute_json<AER::Simulator::QasmController>(j.dump()));
auto results = *results_json["results"].begin();
auto counts = results["data"]["counts"].get<std::map<std::string, int>>();
for (auto &kv : counts) {
std::string hexStr = kv.first;
int nOccurrences = kv.second;
auto bitStr = hex_string_to_binary_string(hexStr);
// Process bitStr to be an n-Measure string in msb
std::string actual = "";
CountGatesOfTypeVisitor<Measure> cc(program);
int nMeasures = cc.countGates();
for (int i = 0; i < nMeasures; i++)
actual += "0";
for (int i = 0; i < nMeasures; i++)
actual[actual.length() - 1 - i] = bitStr[bitStr.length() - i - 1];
buffer->appendMeasurement(actual, nOccurrences);
}
} else {
// statevector
// remove all measures, don't need them
auto tmp = xacc::ir::asComposite(program->clone());
tmp->clear();
InstructionIterator iter(program);
while (iter.hasNext()) {
auto next = iter.next();
if (!next->isComposite() && next->name() != "Measure") {
tmp->addInstruction(next);
}
}
auto qobj_str = xacc_to_qobj->translate(tmp);
nlohmann::json j = nlohmann::json::parse(qobj_str)["qObject"];
auto results_json = nlohmann::json::parse(
AER::controller_execute_json<AER::Simulator::StatevectorController>(
j.dump()));
auto results = *results_json["results"].begin();
auto state_vector = results["data"]["statevector"]
.get<std::vector<std::pair<double, double>>>();
buffer->addExtraInfo("state", state_vector);
// std::cout << "SV measure:\n";
// for (auto& [k,v] : counts) std::cout << k << " : " << v << "\n";
// const auto hasEvenParity =
// [](size_t x, const std::vector<size_t> &in_qubitIndices) -> bool {
// size_t count = 0;
// for (const auto &bitIdx : in_qubitIndices) {
// if (x & (1ULL << bitIdx)) {
// count++;
// }
// }
// return (count % 2) == 0;
// };
// double result = 0.0;
// for (uint64_t i = 0; i < m_stateVec.size(); ++i) {
// result += (hasEvenParity(i, m_measureBits) ? 1.0 : -1.0) *
// std::norm(std::complex<double>(state_vector[i][0], state_vector[i][1]));
// }
// buffer->addExtraInfo("exp-val-z", result);
}
}
void AerAccelerator::execute(
std::shared_ptr<AcceleratorBuffer> buffer,
const std::vector<std::shared_ptr<CompositeInstruction>>
compositeInstructions) {
for (auto &f : compositeInstructions) {
auto tmpBuffer =
std::make_shared<xacc::AcceleratorBuffer>(f->name(), buffer->size());
execute(tmpBuffer, f);
buffer->appendChild(f->name(), tmpBuffer);
}
}
} // namespace quantum
} // namespace xacc
using namespace cppmicroservices;
namespace {
/**
*/
class US_ABI_LOCAL AerActivator : public BundleActivator {
public:
AerActivator() {}
/**
*/
void Start(BundleContext context) {
auto xt = std::make_shared<xacc::quantum::AerAccelerator>();
context.RegisterService<xacc::Accelerator>(xt);
}
/**
*/
void Stop(BundleContext /*context*/) {}
};
} // namespace
CPPMICROSERVICES_EXPORT_BUNDLE_ACTIVATOR(AerActivator)
/*******************************************************************************
* Copyright (c) 2019 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompanies this
* distribution. The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
*License is available at https://eclipse.org/org/documents/edl-v10.php
*
* Contributors:
* Thien Nguyen - initial API and implementation
*******************************************************************************/
#pragma one
#include "xacc.hpp"
#include <nlohmann/json.hpp>
namespace xacc {
namespace quantum {
class AerAccelerator : public Accelerator {
public:
// Identifiable interface impls
const std::string name() const override { return "aer"; }
const std::string description() const override {
return "XACC Simulation Accelerator based on aer library.";
}
// Accelerator interface impls
void initialize(const HeterogeneousMap &params = {}) override;
void updateConfiguration(const HeterogeneousMap &config) override {
initialize(config);
};
const std::vector<std::string> configurationKeys() override { return {}; }
BitOrder getBitOrder() override { return BitOrder::MSB; }
void execute(std::shared_ptr<AcceleratorBuffer> buffer,
const std::shared_ptr<CompositeInstruction> compositeInstruction)
override;
void execute(std::shared_ptr<AcceleratorBuffer> buffer,
const std::vector<std::shared_ptr<CompositeInstruction>>
compositeInstructions) override;
private:
std::shared_ptr<Compiler> xacc_to_qobj;
int m_shots = 1024;
std::string m_simtype = "qasm";
nlohmann::json noise_model;
};
} // namespace quantum
} // namespace xacc
{
"bundle.symbolic_name" : "xacc_aer",
"bundle.activator" : true,
"bundle.name" : "XACC aer Simulation Accelerator",
"bundle.description" : "This bundle provides a aer Accelerator for Gate Model QC."
}
\ No newline at end of file
Copyright 2018 IBM and its contributors
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS