Skip to content

Commit

Permalink
Merge pull request #198 from ScQ-Cloud/xuxs
Browse files Browse the repository at this point in the history
fix: fix python relates issues
  • Loading branch information
Zhaoyilunnn authored Dec 3, 2024
2 parents 87a4e07 + 3573a2b commit 1471e50
Show file tree
Hide file tree
Showing 163 changed files with 9,496 additions and 9,656 deletions.
100 changes: 98 additions & 2 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -1,2 +1,98 @@
DerivePointerAlignment: false
PointerAlignment: Left
BasedOnStyle: Google
AccessModifierOffset: -3
AlignConsecutiveMacros: true
AlignEscapedNewlines: Right
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterExternBlock: false
AfterFunction: false
AfterNamespace: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakBeforeBinaryOperators: All
BreakBeforeBraces: Custom
BreakBeforeConceptDeclarations: true
BreakBeforeInheritanceComma: true
BreakConstructorInitializers: BeforeComma
ColumnLimit: 120
CompactNamespaces: false
FixNamespaceComments: true
IncludeBlocks: Regroup
IncludeCategories:
# We define the include categories such that the header files are sorted and grouped as follows:
# 1. C standard headers
# 2. C++ standard headers
# 3. CUDA headers
# 4. Boost headers
# 5. Eigen headers
# 8. Other system headers
# 9. Any local config header
# 10. Local headers
# 11. Catch2 headers
- Regex: '[<"](catch2/([A-Za-z0-9.\/\-_])+)[>"]' # Make sure Catch2 is included last
Priority: 110
- Regex: '[<"]tweedledum/([A-Za-z0-9.\/\-_])+[>"]'
Priority: 60
- Regex: <boost\/
Priority: 40
- Regex: <(Eigen|Unsupported/Eigen)\/
Priority: 50
- Regex: '[<"]cuda[A-Za-z0-9.\/\-_]+[>"]'
Priority: 30
- Regex: '[<"](driver_types.h)[>"]'
Priority: 30
- Regex: >-
'<
(assert|complex|ctype|errno|fenv|float|inttypes|iso646|limits|locale|math|setjmp|signal|stdalign|stdarg
|stdatomic|stdbool|stddef|stdint|stdio|stdlib|stdnoreturn|string|tdmath|threads|time|uchar|wchar|wctype)
\.h>'
Priority: 10
- Regex: <[[:alnum:]_\.]+.h>
Priority: 10
- Regex: <[[:alnum:]_\.]+>
Priority: 20
- Regex: <[[:alnum:]_\.]+
Priority: 80
- Regex: '"config/[[:alnum:]\/\-_\.]+\.hpp"'
Priority: 90
- Regex: '"python/[[:alnum:]\/\-_\.]+"'
Priority: 110
- Regex: '"[[:alnum:]\/\-_\.]+"'
Priority: 100
IndentPPDirectives: AfterHash
IndentRequires: true
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: false
NamespaceIndentation: None
PenaltyBreakAssignment: 40
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
StatementMacros: []
TypenameMacros: []
Standard: Latest
TabWidth: 4
UseTab: Never
WhitespaceSensitiveMacros: [CLANG_DIAG_ON, CLANG_DIAG_OFF, GCC_DIAG_ON, GCC_DIAG_OFF, MSVC_DIAG_ON, MSVC_DIAG_OFF, MQ_DO_PRAGMA]
Empty file added .cppcheck.suppressions
Empty file.
87 changes: 69 additions & 18 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
repos:
- repo: https://github.com/Lucas-C/pre-commit-hooks.git
rev: v1.5.4
rev: v1.5.5
hooks:
- id: remove-crlf
files: (?!.*third_party)^.*$ | (?!.*book)^.*$
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v5.0.0
hooks:
- id: check-added-large-files
args:
Expand All @@ -18,36 +18,87 @@ repos:
- id: trailing-whitespace
- id: requirements-txt-fixer
- id: sort-simple-yaml
- repo: https://github.com/pylint-dev/pylint
rev: v3.0.0a6

- repo: https://gitee.com/mirrors_PyCQA/pylint
rev: v3.3.1
hooks:
- id: pylint
args:
- --disable=all
- --load-plugins=docstring_checker
- --enable=doc-string-one-line,doc-string-end-with,doc-string-with-all-args,doc-string-triple-quotes,doc-string-missing,doc-string-indent-error,doc-string-with-returns,doc-string-with-raises
name: pylint-strict
exclude: (.*_test\.py)$
args: [--score=n, --load-plugins=pylint_secure_coding_standard]
additional_dependencies: [pylint-secure-coding-standard, numpy, pytest, matplotlib, scipy, torch, requests, graphviz, tabulate, rich, sparse, autograd, ply]

- repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks.git
rev: v2.10.0
rev: v2.14.0
hooks:
- id: pretty-format-yaml
args: [--autofix, --indent, '4']
- repo: https://github.com/hadialqattan/pycln
rev: v2.2.2
rev: v2.4.0
hooks:
- id: pycln
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v15.0.7
hooks:
- id: clang-format
args: [-style=file]
# Using this mirror lets us use mypyc-compiled black, which is about 2x faster
# - repo: https://github.com/pre-commit/mirrors-clang-format
# rev: v15.0.7
# hooks:
# - id: clang-format
# args: [-style=file]
# Using this mirror lets us use mypyc-compiled black, which is about 2x faster
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.12.0
rev: 24.10.0
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.12.0
rev: 5.13.2
hooks:
- id: isort
name: isort (python)
args: [--profile, black, --filter-files]

- repo: https://gitee.com/dnguyen/cmake-pre-commit-hooks-mirror
rev: v1.5.3
hooks:
# - id: clang-format
# require_serial: false
# args: [-i]
# files: .*\.(h|hpp|tpp|cpp|cc)$
# additional_dependencies: [clang-format==14.*]
# - id: cpplint
# require_serial: false
# args: [--quiet]
# files: .*\.(h|hpp|tpp|cpp|cc)$
# additional_dependencies: [cpplint]
- id: lizard
require_serial: false
files: .*\.(h|hpp|tpp|cpp|cc|py)$
args: [-l, cpp, -l, python, -l, java, -C, '19', -L, '100', -x, '*/tests/*', -x, '*/test/*', -x, '*/third_party/*', -W.whitelizard.txt, -w]
additional_dependencies: [lizard]
# - id: clang-tidy
# stages: [manual]
# args: [-Bbuild, -B.pre-commit-build]
# exclude: >-
# (?x)^(
# .*/kernel[0-9]+\.hpp|
# .*third_party/.*|
# .*\.cu
# )$

# TODO: Ignore cpp file check.
# - repo: https://gitee.com/btcong/pre-commit-hooks
# rev: v1.3.5
# hooks:
# - id: cppcheck
# files: .*\.(h|hpp|tpp|cpp|cc)$
# args: [--force, --enable=all, --error-exitcode=1, --inline-suppr, --std=c++14, --language=c++, --suppressions-list=.cppcheck.suppressions]

- repo: https://gitee.com/mirrors/flake8
rev: 5.0.4
hooks:
- id: flake8
args: [--docstring-convention, google]
name: flake8-strict
exclude: (.*_test\.py)$
additional_dependencies: [flake8-breakpoint, flake8-builtins, flake8-comprehensions, flake8-continuation, flake8-docstrings, flake8-eradicate, flake8-mutable, flake8-return, pep8-naming, flake8-secure-coding-standard]
- id: flake8
name: flake8-test-files
files: (.*_test\.py)$
additional_dependencies: [flake8-breakpoint, flake8-builtins, flake8-comprehensions, flake8-continuation, flake8-eradicate, flake8-mutable, flake8-return]
14 changes: 14 additions & 0 deletions .whitelizard.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
quafu/transpiler/compiler/compiler_visualization.py:compile_vis
quafu/qfasm/qfasm_parser.py:handle_gateins
quafu/circuits/quantum_circuit.py:layered_circuit
quafu/circuits/quantum_circuit.py:draw_circuit


src/qfvm/statevector.hpp:StateVector<real_t>::apply_cz.StateVector<real_t>::apply_one_targe_gate_general
src/qfvm/statevector.hpp:StateVector<real_t>::apply_cz.StateVector<real_t>::apply_one_targe_gate_x
src/qfvm/statevector.hpp:StateVector<real_t>::apply_cz.StateVector<real_t>::apply_one_targe_gate_real
src/qfvm/statevector.hpp:StateVector<real_t>::apply_cz.StateVector<real_t>::apply_one_targe_gate_diag
src/qfvm/statevector.hpp:StateVector<real_t>::apply_cz.StateVector<real_t>::apply_diagonal_matrix
src/qfvm_gpu/cuda_utils/helper_string.h:sdkFindFilePath
src/qfvm_gpu/cuda_utils/helper_cuda.h:_cudaGetErrorEnum
src/qfvm/simulator.hpp:apply_op
4 changes: 4 additions & 0 deletions CPPLINT.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
set noparent
headers=cuh,h,h++,hh,hpp,hxx,tpp
linelength=120
filter=-build/header_guard,-build/c++11
6 changes: 3 additions & 3 deletions doc/source/versions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"0.4.0": {
"tag": "tags/v0.4.0"
}
"0.4.0": {
"tag": "tags/v0.4.0"
}
}
13 changes: 3 additions & 10 deletions examples/quantum_rl/misc/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,14 @@ def get_obs_policy(obsw, beta):
"""
Output the final policy.
"""
process = tf.keras.Sequential(
return tf.keras.Sequential(
[
Alternating_(obsw),
tf.keras.layers.Lambda(lambda x: x * beta),
tf.keras.layers.Softmax(),
],
name="obs_policy",
)
return process


def get_height(position):
Expand Down Expand Up @@ -171,10 +170,7 @@ def gather_episodes(

while not all(done):
unfinished_ids = [i for i in range(n_episodes) if not done[i]]
normalized_states = [
s / state_bounds for i, s in enumerate(states) if not done[i]
]
# height = [get_height(s[0]) for i, s in enumerate(states) if not done[i]]
normalized_states = [s / state_bounds for i, s in enumerate(states) if not done[i]]

for i, state in zip(unfinished_ids, normalized_states):
trajectories[i]["states"].append(state)
Expand All @@ -186,12 +182,9 @@ def gather_episodes(
action_probs = model([states])
elif backend == "quafu":
newtheta, newlamda = get_model_circuit_params(qubits, genotype, model)
circuit, _, _ = generate_circuit(
qubits, genotype, newtheta, newlamda, states.numpy()[0]
)
circuit, _, _ = generate_circuit(qubits, genotype, newtheta, newlamda, states.numpy()[0])
taskid, expectation = get_quafu_exp(circuit, n_qubits, backend_quafu, shots)
tasklist.append(taskid)
# print('gather_episodes_exp:', expectation)

obsw = model.get_layer("observables-policy").get_weights()[0]
obspolicy = get_obs_policy(obsw, beta)
Expand Down
45 changes: 18 additions & 27 deletions examples/quantum_rl/models/quantum_models.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import cirq
import models.quantum_genotypes as genotypes
import numpy as np
import tensorflow as tf
import tensorflow_quantum as tfq
from models.quantum_operations import *
from models.quantum_operations import OPS


def generate_circuit(qubits, genotype, newtheta=None, newlamda=None, state=None):
Expand All @@ -13,37 +12,37 @@ def generate_circuit(qubits, genotype, newtheta=None, newlamda=None, state=None)
op_entangle, pos_entangle = zip(*genotype.entangle)
op_measure, pos_measure = zip(*genotype.measure)

dict = {}
dict_data = {}
for name, pos in zip(op_vpqc, pos_vpqc):
dict[pos] = name
dict_data[pos] = name
for name, pos in zip(op_dpqc, pos_dpqc):
dict[pos] = name
dict_data[pos] = name
for name, pos in zip(op_entangle, pos_entangle):
dict[pos] = name
dict_data[pos] = name
for name, pos in zip(op_measure, pos_measure):
dict[pos] = name
length = len(dict)
dict_data[pos] = name
length = len(dict_data)

circuit = cirq.Circuit()
params = []
inputs = []
p_count = 0
i_count = 0
for i in range(length):
if dict[i] == "variationalPQC":
cir, pa = OPS[dict[i]](qubits, p_count, newtheta)
if dict_data[i] == "variationalPQC":
cir, pa = OPS[dict_data[i]](qubits, p_count, newtheta)
circuit += cir
params += pa
p_count += 1
elif dict[i] == "dataencodingPQC":
cir, inp = OPS[dict[i]](qubits, i, i_count, newlamda, state)
elif dict_data[i] == "dataencodingPQC":
cir, inp = OPS[dict_data[i]](qubits, i, i_count, newlamda, state)
circuit += cir
inputs += inp
i_count += 1
elif dict[i] == "entanglement":
cir = OPS[dict[i]](qubits)
elif dict_data[i] == "entanglement":
cir = OPS[dict_data[i]](qubits)
circuit += cir
elif dict[i] == "measurement":
elif dict_data[i] == "measurement":
pass
else:
raise NameError("Unknown quantum genotype operation")
Expand Down Expand Up @@ -79,9 +78,7 @@ def get_model_circuit_params(qubits, genotype, model):
class NSGANetPQC(tf.keras.layers.Layer):
"""Define NSGANet PQC based on keras layer"""

def __init__(
self, qubits, genotype, observables, activation="linear", name="nsganet_PQC"
):
def __init__(self, qubits, genotype, observables, activation="linear", name="nsganet_PQC"):
super(NSGANetPQC, self).__init__(name=name)
self.n_qubits = len(qubits)
_, pos_dpqc = zip(*genotype.dpqc)
Expand All @@ -97,9 +94,7 @@ def __init__(
)

lmbd_init = tf.ones(shape=(self.n_qubits * self.n_layers,))
self.lmbd = tf.Variable(
initial_value=lmbd_init, dtype="float32", trainable=True, name="lambdas"
)
self.lmbd = tf.Variable(initial_value=lmbd_init, dtype="float32", trainable=True, name="lambdas")

# Define explicit symbol order.
symbols = [str(symb) for symb in theta_symbols + input_symbols]
Expand Down Expand Up @@ -156,9 +151,7 @@ def call(self, inputs):

def generate_model_policy(qubits, genotype, n_actions, beta, observables, env):
"""Generate a Keras model for a NSGANet PQC policy."""
input_tensor = tf.keras.Input(
shape=(len(qubits),), dtype=tf.dtypes.float32, name="input"
)
input_tensor = tf.keras.Input(shape=(len(qubits),), dtype=tf.dtypes.float32, name="input")
nsganet_pqc = NSGANetPQC(qubits, genotype, observables)([input_tensor])
process = tf.keras.Sequential(
[
Expand All @@ -169,6 +162,4 @@ def generate_model_policy(qubits, genotype, n_actions, beta, observables, env):
name="observables-policy",
)
policy = process(nsganet_pqc)
model = tf.keras.Model(inputs=[input_tensor], outputs=policy)

return model
return tf.keras.Model(inputs=[input_tensor], outputs=policy)
Loading

0 comments on commit 1471e50

Please sign in to comment.