quantumlib / Qualtran

Qᴜᴀʟᴛʀᴀɴ is a Python library for expressing and analyzing Fault Tolerant Quantum algorithms.
https://qualtran.readthedocs.io/en/latest/
Apache License 2.0
173 stars 40 forks source link

`BloqInstance.i` index should not be an arbitrary index and should preserve insertion ordering #1098

Open tanujkhattar opened 3 months ago

tanujkhattar commented 3 months ago

I think it would be nice if BloqInstance.i has some semantic meaning in the context of a CompositeBloq. Some possible options are:

It seems like these properties break down because of

https://github.com/quantumlib/Qualtran/blob/79a880bc6e8c4069a9871cafe83a28911675083e/qualtran/_infra/composite_bloq.py#L346-L352

Is there a particular reason we chose to preserve this property where binst.i of bloqs which are not flattened is preserved? @mpharrigan

I'm particularly interested to query the following property:

This is useful for a PR I'm working on to provide a greedy topological sorting with a heuristic that aims to help minimize qubit allocations / deallocations and would be useful for qubit count costs (xref https://github.com/quantumlib/Qualtran/issues/1097) and translation of a composite bloq to a cirq circuit (xref comment by Anurudh https://github.com/quantumlib/Qualtran/pull/963#issuecomment-2192745758)

mpharrigan commented 3 months ago

As noted, that's to support drawing circuits where you can flatten only parts of it while keeping the identity of the unmodified parts the same

tanujkhattar commented 3 months ago

Do the drawings specifically depend upon the value of binst.i ? Can you point me to where that happens?

mpharrigan commented 3 months ago

It's used in the prototype interactive drawing musical_score.js which will tween between the top-level circuit and a partially decompose&flattened one. binst.i is the "key" that d3.js uses to know which things in the original circuit correspond to which in the decomposed one

tanujkhattar commented 3 months ago

One way to satisfy both the requirements would be to make binst.i a tuple instead of an index; then as we decompose we can keep appending to the tuple and the property that binst1.i < binst2.i preserves insertion ordering would also be satisfied. We can cache the hash if we think this would add a performance bottleneck. WDYT ?

mpharrigan commented 3 months ago

I think there are ways to preserve the insertion index. An easy one would be to have the CompositeBloq._bloq_instances attribute be an ordered list. In general, I'd be happier if the insertion order was kept within the context of the container rather than on the BloqInstance itself. Another option would be to have an additional field on BloqInstance that is the insertion order. Keeping the i as an arbitrary identifier that is preserved through flattening makes conceptual sense to me.