# Reshaping the 4x4 CNOT gate into 2x2x2x2 in a tensor network

I'm learning how to perform tensor network contraction for simulating a quantum circuit by looking at the documentation for the JET simulator: link. Specifically, I'm trying to do all the calculations (contraction) by hand to get a sense of what is actually happening.

When mapping the above entanglement circuit into the tensor network below, it's easy to construct the 1-qubit Hadamard gate, we just use the 2x2 matrix because it also happens to be a rank-2 tensor.

However, the CNOT tensor is a rank-4 tensor, so we cannot use the 4x4 CNOT matrix directly, we have to reshape it to 2x2x2x2, and this is how they did it in the document:

I can see that this is just reshaping the original CNOT matrix row-by-row into a 2x2x2x2 matrix, but my questions are:

1. why are we reshaping in this order? (in code, the index order is k, j, m, n)
2. does order matter? (like can I construct the CNOT tensor using Tensor CNOT({"k", "m", "j", "n"}, {2, 2, 2, 2});?)
3. what's the general procedure when reshaping gate matrix into higher ranks? (for example, to reshape the 8x8 Toffoli gate into 2x2x2x2x2x2, because it's going to be a rank-6 tensor.)

Also, their code FYI:

Tensor CNOT({"k", "j", "m", "n"}, {2, 2, 2, 2});
CNOT.SetValue({0, 0, 0, 0}, 1); // |00> -> |00>
CNOT.SetValue({0, 1, 0, 1}, 1); // |01> -> |01>
CNOT.SetValue({1, 0, 1, 1}, 1); // |10> -> |11>
CNOT.SetValue({1, 1, 1, 0}, 1); // |11> -> |10>

• I discussed a similar issue here idnm.github.io/blog/qiskit/tensor%20networks/quantum%20concepts/… in the context of the tensornetwork library, although I' not sure that there are no gotchas in passing from tensornetwork notation to JET. Commented May 20, 2022 at 11:30
• @NikitaNemkov Thanks for the blog post! I tried your example about connecting two identity matrices in the wrong way to produce a SWAP gate. If I understand you correctly, you meant connecting a[2] ^ b[1] and a[3] ^ b[0] right? Also, I'm still wondering why you're assigning the "0123" labels on the legs in that sequence, in JET they're also assigning the indices in this order ("kjmn"), do we HAVE to do it like this? If so, what's the reasoning behind this? I've tried to change the order to "jkmn" and I can still get the correct output.
– Mao
Commented May 21, 2022 at 4:28
• sorry, this is a bit hard to discuss in comments. Important thing is how the legs of the original tensor correspond to the legs of the reshaped tensor. You've said that "kjmn" gives you the same results as "jkmn", is it for CNOT of for a random tensor? I think it is better to work with random tensors, since they have no symmetry that can obscure things in this context. Commented May 21, 2022 at 15:15
• @NikitaNemkov I see, I was only working with the CNOT matrix, and I found that "mnkj" will output the wrong result. I will try more examples with random tensors, thank you!
– Mao
Commented May 23, 2022 at 4:57