Repository navigation
Conversation
|
@adlantz Thank you for the benchmarks in the PR description. Could you also attach the benchmark script? |
|
@mhucka Here are the two scripts I used. First is to profile Profile convert_to_tensor()And here is the script that benchmarks the before and after of replacing the deep copy. Benchmark before and after changesAnd here is a little guide on actually running these scripts: Running the benchmark scriptsBoth scripts are attached above. They aren't part of this PR's diff. 1. Check out this branch git clone https://github.com/tensorflow/quantum.git && cd quantum
git fetch origin pull/1114/head:serialize-shallow-copy
git checkout serialize-shallow-copy2. Install TFQ into a virtualenv. The scripts import the installed python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
./configure.sh
bazel build -c opt release:build_pip_package
./bazel-bin/release/build_pip_package /tmp/tfquantum/
pip install /tmp/tfquantum/*.whl3. Save both scripts in the repo root. They find the repo from their own location and read 4. Run them # A/B: master's serialize_circuit vs. this branch, with an output-equality check
python ab_benchmark_serializer.py # --markdown for a table, --quick for a fast check
# Where convert_to_tensor spends its time (pre-change code)
python profile_convert_to_tensor.py --serializer-ref master # add --profile for a cProfile breakdownNotes:
|
Issue #336 asks for improvements to the
tfq.convert_to_tensor speedfunction. The majorirty of the run time occurs in the cirq serialization logic:Inspecting
serialize_circuitI noticed a quick win would be to not do a full deep copy of the input circuit, instead create a shallow copy withcircuit = circuit_inp.copy(). The risk with this is that we may modify the input circuit (change in behavior). We can get away with this because moments are replaces rather than edited in place by the serializer, i.eThat being said, in the controlled operations demotion loop, we reference and mutate
op.sub_operationwhich points to an attribute on the input circuit. Therefore, we make a copy there of each sub operation.Overall the speedup is significant:
The downside is less peace of mind that the input circuit is not mutated, and any changes here in the future need to keep that in mind.
I added a test to ensure serialization does not mutate the input circuit.