Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
f55a374
the 3 files
Gruntrexpewrus Mar 23, 2022
47a3ffc
add benchmarks quantum kernel/QKT
Gruntrexpewrus Mar 23, 2022
fe06340
Merge branch 'Qiskit:main' into main
Gruntrexpewrus Apr 11, 2022
d50db30
Maybe fixed errors?
Gruntrexpewrus Apr 11, 2022
bd1a015
changes on codes and syntac, bug found maybe is solved, probably not …
Gruntrexpewrus May 11, 2022
0074742
Merge branch 'main' into main
Gruntrexpewrus May 11, 2022
e8a4dca
running locally
Gruntrexpewrus May 17, 2022
b9362f8
Merge branch 'main' of https://github.com/Gruntrexpewrus/qiskit-app-b…
Gruntrexpewrus May 17, 2022
1a5ce77
fixed pylint
Gruntrexpewrus May 17, 2022
d36397c
fixed typos
Gruntrexpewrus May 18, 2022
80ebca7
fix typos
Gruntrexpewrus May 18, 2022
f350849
typos
Gruntrexpewrus May 18, 2022
eb17e59
typos
Gruntrexpewrus May 18, 2022
8eb11d4
fixed some errors
Gruntrexpewrus May 18, 2022
f363319
Merge branch 'main' into main
manoelmarques May 19, 2022
1a90447
Merge branch 'main' into main
manoelmarques Jun 1, 2022
0c66dbc
adjusted benchmarks, still 2 errors
Gruntrexpewrus Jun 2, 2022
e2f16f1
Merge branch 'main' of https://github.com/Gruntrexpewrus/qiskit-app-b…
Gruntrexpewrus Jun 2, 2022
2415e33
Merge branch 'main' of https://github.com/Gruntrexpewrus/qiskit-app-b…
Gruntrexpewrus Jun 3, 2022
edaf922
test
a-matsuo Jun 6, 2022
3d5fe75
Merge branch 'main' into main
manoelmarques Jun 17, 2022
e7aa5fb
Merge branch 'main' into main
manoelmarques Sep 6, 2022
a44eb21
Merge branch 'main' into main
manoelmarques Dec 11, 2022
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
184 changes: 184 additions & 0 deletions asv.conf.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
{
// The version of the config file format. Do not change, unless
// you know what you are doing.
"version": 1,

// The name of the project being benchmarked
"project": "project",

// The project's homepage
"project_url": "http://project-homepage.org/",

// The URL or local path of the source code repository for the
// project being benchmarked
"repo": ".",

// The Python project's subdirectory in your repo. If missing or
// the empty string, the project is assumed to be located at the root
// of the repository.
// "repo_subdir": "",

// Customizable commands for building, installing, and
// uninstalling the project. See asv.conf.json documentation.
//
// "install_command": ["in-dir={env_dir} python -mpip install {wheel_file}"],
// "uninstall_command": ["return-code=any python -mpip uninstall -y {project}"],
// "build_command": [
// "python setup.py build",
// "PIP_NO_BUILD_ISOLATION=false python -mpip wheel --no-deps --no-index -w {build_cache_dir} {build_dir}"
// ],

// List of branches to benchmark. If not provided, defaults to "master"
// (for git) or "default" (for mercurial).
// "branches": ["master"], // for git
// "branches": ["default"], // for mercurial

// The DVCS being used. If not set, it will be automatically
// determined from "repo" by looking at the protocol in the URL
// (if remote), or by looking for special directories, such as
// ".git" (if local).
// "dvcs": "git",

// The tool to use to create environments. May be "conda",
// "virtualenv" or other value depending on the plugins in use.
// If missing or the empty string, the tool will be automatically
// determined by looking for tools on the PATH environment
// variable.
"environment_type": "virtualenv",

// timeout in seconds for installing any dependencies in environment
// defaults to 10 min
//"install_timeout": 600,

// the base URL to show a commit for the project.
// "show_commit_url": "http://github.com/owner/project/commit/",

// The Pythons you'd like to test against. If not provided, defaults
// to the current version of Python used to run `asv`.
// "pythons": ["2.7", "3.6"],

// The list of conda channel names to be searched for benchmark
// dependency packages in the specified order
// "conda_channels": ["conda-forge", "defaults"],

// A conda environment file that is used for environment creation.
// "conda_environment_file": "environment.yml",

// The matrix of dependencies to test. Each key of the "req"
// requirements dictionary is the name of a package (in PyPI) and
// the values are version numbers. An empty list or empty string
// indicates to just test against the default (latest)
// version. null indicates that the package is to not be
// installed. If the package to be tested is only available from
// PyPi, and the 'environment_type' is conda, then you can preface
// the package name by 'pip+', and the package will be installed
// via pip (with all the conda available packages installed first,
// followed by the pip installed packages).
//
// The ``@env`` and ``@env_nobuild`` keys contain the matrix of
// environment variables to pass to build and benchmark commands.
// An environment will be created for every combination of the
// cartesian product of the "@env" variables in this matrix.
// Variables in "@env_nobuild" will be passed to every environment
// during the benchmark phase, but will not trigger creation of
// new environments. A value of ``null`` means that the variable
// will not be set for the current combination.
//
// "matrix": {
// "req": {
// "numpy": ["1.6", "1.7"],
// "six": ["", null], // test with and without six installed
// "pip+emcee": [""] // emcee is only available for install with pip.
// },
// "env": {"ENV_VAR_1": ["val1", "val2"]},
// "env_nobuild": {"ENV_VAR_2": ["val3", null]},
// },

// Combinations of libraries/python versions can be excluded/included
// from the set to test. Each entry is a dictionary containing additional
// key-value pairs to include/exclude.
//
// An exclude entry excludes entries where all values match. The
// values are regexps that should match the whole string.
//
// An include entry adds an environment. Only the packages listed
// are installed. The 'python' key is required. The exclude rules
// do not apply to includes.
//
// In addition to package names, the following keys are available:
//
// - python
// Python version, as in the *pythons* variable above.
// - environment_type
// Environment type, as above.
// - sys_platform
// Platform, as in sys.platform. Possible values for the common
// cases: 'linux2', 'win32', 'cygwin', 'darwin'.
// - req
// Required packages
// - env
// Environment variables
// - env_nobuild
// Non-build environment variables
//
// "exclude": [
// {"python": "3.2", "sys_platform": "win32"}, // skip py3.2 on windows
// {"environment_type": "conda", "req": {"six": null}}, // don't run without six on conda
// {"env": {"ENV_VAR_1": "val2"}}, // skip val2 for ENV_VAR_1
// ],
//
// "include": [
// // additional env for python2.7
// {"python": "2.7", "req": {"numpy": "1.8"}, "env_nobuild": {"FOO": "123"}},
// // additional env if run on windows+conda
// {"platform": "win32", "environment_type": "conda", "python": "2.7", "req": {"libpython": ""}},
// ],

// The directory (relative to the current directory) that benchmarks are
// stored in. If not provided, defaults to "benchmarks"
// "benchmark_dir": "benchmarks",

// The directory (relative to the current directory) to cache the Python
// environments in. If not provided, defaults to "env"
"env_dir": ".asv/env",

// The directory (relative to the current directory) that raw benchmark
// results are stored in. If not provided, defaults to "results".
"results_dir": ".asv/results",

// The directory (relative to the current directory) that the html tree
// should be written to. If not provided, defaults to "html".
"html_dir": ".asv/html",

// The number of characters to retain in the commit hashes.
// "hash_length": 8,

// `asv` will cache results of the recent builds in each
// environment, making them faster to install next time. This is
// the number of builds to keep, per environment.
// "build_cache_size": 2,

// The commits after which the regression search in `asv publish`
// should start looking for regressions. Dictionary whose keys are
// regexps matching to benchmark names, and values corresponding to
// the commit (exclusive) after which to start looking for
// regressions. The default is to start from the first commit
// with results. If the commit is `null`, regression detection is
// skipped for the matching benchmark.
//
// "regressions_first_commits": {
// "some_benchmark": "352cdf", // Consider regressions only after this commit
// "another_benchmark": null, // Skip regression detection altogether
// },

// The thresholds for relative change in results, after which `asv
// publish` starts reporting regressions. Dictionary of the same
// form as in ``regressions_first_commits``, with values
// indicating the thresholds. If multiple entries match, the
// maximum is taken. If no entry matches, the default is 5%.
//
// "regressions_thresholds": {
// "some_benchmark": 0.01, // Threshold of 1%
// "another_benchmark": 0.5, // Threshold of 50%
// },
}
1 change: 1 addition & 0 deletions benchmarks/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

31 changes: 31 additions & 0 deletions benchmarks/benchmarks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Write the benchmarking functions here.
# See "Writing benchmarks" in the asv docs for more information.


class TimeSuite:
"""
An example benchmark that times the performance of various kinds
of iterating over dictionaries in Python.
"""
def setup(self):
self.d = {}
for x in range(500):
self.d[x] = None

def time_keys(self):
for key in self.d.keys():
pass

def time_values(self):
for value in self.d.values():
pass

def time_range(self):
d = self.d
for key in range(500):
x = d[key]


class MemSuite:
def mem_list(self):
return [0] * 256
98 changes: 98 additions & 0 deletions machine_learning/benchmarks/qk_base_benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Base class for QuantumKernel and QuantumKernelTraining based classifier benchmarks."""
from abc import ABC
from typing import Optional

from qiskit.algorithms.optimizers import Optimizer
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, FunctionTransformer

import numpy as np

from .base_classifier_benchmark import BaseClassifierBenchmark


class QKernelBaseClassifierBenchmark(BaseClassifierBenchmark, ABC):
"""Base class for quantum kernel benchmarks."""

def __init__(self) -> None:
reshaper = FunctionTransformer(lambda x: x.reshape(-1, 1))
encoder = OneHotEncoder(sparse=False)
super().__init__(
synthetic_label_encoder=Pipeline([("reshape", reshaper), ("one hot", encoder)]),
iris_num_classes=2,
iris_label_encoder=Pipeline([("reshape", reshaper), ("one hot", encoder)]),
)

def _construct_quantumkernel_classical_classifier(
self,
quantum_instance_name: str,
method="quantumclassical",
num_qubits=1,
) -> QuantumKernel:
"""This method just create the matrix from the quantum kernel"""
kernelmatrix = self._construct_quantumkernel(num_qubits, quantum_instance_name, method)
return kernelmatrix

def _construct_quantumkerneltrainer(
self,
quantum_instance_name: str,
optimizer: Optional[Optimizer] = None,
loss_function: str = None,
method="quantum",
num_qubits=1,
) -> QuantumKernelTrainer:
"""This method returns the quantumkerneltrainer"""
kernel = self._construct_quantumkernel(num_qubits, quantum_instance_name, method)
qkt = QuantumKernelTrainer(
quantum_kernel=kernel,
loss=loss_function,
optimizer=optimizer,
initial_point=[np.pi / 2],
)
return qkt

def _construct_quantumkernel(
self,
num_inputs: int,
quantum_instance_name: str,
method: str,
) -> QuantumKernel:
"""Construct a QuantumKernel"""
if method == "quantumclassical":
feature_map = ZZFeatureMap(num_inputs, reps=2, entanglement="linear")
qkernel = QuantumKernel(
feature_map=feature_map, quantum_instance=self.backends[quantum_instance_name]
)
return qkernel
elif method == "quantum":
user_params = ParameterVector("θ", 1)
fm0 = QuantumCircuit(num_inputs)
for i in range(num_inputs):
fm0.ry(user_params[0], i)
fm1 = ZZFeatureMap(num_inputs, reps=2, entanglement="linear")
feature_map = fm0.compose(fm1)
qkernel = QuantumKernel(
feature_map=feature_map,
user_parameters=user_params,
quantum_instance=self.backends[quantum_instance_name],
)
return qkernel
else:
return ValueError(f"Unsupported method: {method}")
Loading