Copy and deepcopy of a non-parametrized operation only references `op.matrix`
See original GitHub issueIssue description
When copying a non-parametrized operation, e.g. CNOT, the matrix is only copied as a reference. This is the case when using both copy.copy
and copy.deepcopy
. The following:
import pennylane as qml
import copy
op = qml.CNOT(wires=[0,1])
op2 = copy.copy(op)
op3 = copy.deepcopy(op)
print("Before:")
print(op2.matrix)
print(op3.matrix)
op.matrix[0, 0] = 9
print("\nAfter:")
print(op2.matrix)
print(op3.matrix)
outputs:
Before:
[[1 0 0 0]
[0 1 0 0]
[0 0 0 1]
[0 0 1 0]]
[[1 0 0 0]
[0 1 0 0]
[0 0 0 1]
[0 0 1 0]]
After:
[[9 0 0 0]
[0 1 0 0]
[0 0 0 1]
[0 0 1 0]]
[[9 0 0 0]
[0 1 0 0]
[0 0 0 1]
[0 0 1 0]]
-
Expected behavior: (What you expect to happen) I would expect at least deepcopy to make a deep copy of all the internal data.
-
Actual behavior: (What actually happens) Only references are being made to the internally saved matrix.
-
Reproduces how often: (What percentage of the time does it reproduce?) Every time
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (6 by maintainers)
Top Results From Across the Web
copy — Shallow and deep copy operations — Python 3.11.1 ...
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in...
Read more >Shallow Copy and Deep Copy in C++ - GeeksforGeeks
Shallow Copy: In shallow copy, an object is created by simply copying the data of all variables of the original object. This works...
Read more >Deep vs. Shallow copying.
A deep copy means actually creating a new array and copying over the values. The above code shows deep copying. Changes to the...
Read more >What is the difference between shallow copy, deepcopy and ...
The difference between shallow and deep copying is only relevant for ... An assignment operation simply assigns the reference of source to destination...
Read more >Top 170 Machine Learning Interview Questions 2023
What is the difference between deep learning and machine learning? ... a new list) but for everything inside old list, only their reference...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
For the CNOT case, the matrix is a class variable, so even independent objects have correlated
matrix
values:I lean towards not, since we can’t properly distinguish between PL itself performing deepcopies or users performing deepcopies. The core itself might create deepcopies, which would result in a cascade of warnings appearing to unexpected users 😆