Repository: PennyLaneAI/pennylane
Pull request #5945 (2024-07-04 14:22:40)

Fixes `split_non_commuting` with non-trainable autograd coefficients
Honestly, I don't really understand what the root issue is, and I don't really understand why this fixes it.

But it does 🤷

Fixes https://github.com/PennyLaneAI/pennylane/issues/5924
[sc-67508]

github-actions[bot]: Hello. You may have forgotten to update the changelog!
Please edit [`doc/releases/changelog-dev.md`](/PennyLaneAI/pennylane/blob/master/doc/releases/changelog-dev.md) with:
* A one-to-two sentence description of the change. You may include a small working example for new features.
* A link back to this PR.
* Your name (or GitHub username) in the contributors section.
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/5945?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Please [upload](https://docs.codecov.com/docs/codecov-uploader) report for BASE (`v0.37.0-rc0@467e9e5`). [Learn more](https://docs.codecov.io/docs/error-reference?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI#section-missing-base-commit) about missing BASE report.

<details><summary>Additional details and impacted files</summary>


```diff
@@              Coverage Diff               @@
##             v0.37.0-rc0    #5945   +/-   ##
==============================================
  Coverage               ?   99.66%           
==============================================
  Files                  ?      425           
  Lines                  ?    40462           
  Branches               ?        0           
==============================================
  Hits                   ?    40328           
  Misses                 ?      134           
  Partials               ?        0           
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/5945?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI).


Patch:
diff --git a/doc/releases/changelog-0.37.0.md b/doc/releases/changelog-0.37.0.md
index ad4c67b77..a85f791a5 100644
--- a/doc/releases/changelog-0.37.0.md
+++ b/doc/releases/changelog-0.37.0.md
@@ -354,6 +354,7 @@
   [(#5828)](https://github.com/PennyLaneAI/pennylane/pull/5828)
   [(#5869)](https://github.com/PennyLaneAI/pennylane/pull/5869)
   [(#5939)](https://github.com/PennyLaneAI/pennylane/pull/5939)
+  [(#5945)](https://github.com/PennyLaneAI/pennylane/pull/5945)
 
 * `qml.devices.LegacyDevice` is now an alias for `qml.Device`, so it is easier to distinguish it from
   `qml.devices.Device`, which follows the new device API.
diff --git a/pennylane/transforms/split_non_commuting.py b/pennylane/transforms/split_non_commuting.py
index 1f52e243f..90566b92d 100644
--- a/pennylane/transforms/split_non_commuting.py
+++ b/pennylane/transforms/split_non_commuting.py
@@ -701,6 +701,8 @@ def _sum_terms(res: ResultBatch, coeffs: List[float], offset: float, shape: Tupl
     # The shape of res at this point is (n_terms, [,n_shots] [,batch_size])
     dot_products = []
     for c, r in zip(coeffs, res):
+        if qml.math.get_interface(r) == "autograd":
+            r = qml.math.array(r)
         dot_products.append(qml.math.dot(qml.math.squeeze(r), c))
     if len(dot_products) == 0:
         return qml.math.ones(shape) * offset


Test patch:
diff --git a/tests/transforms/test_split_non_commuting.py b/tests/transforms/test_split_non_commuting.py
index fccb53949..5a64b9cda 100644
--- a/tests/transforms/test_split_non_commuting.py
+++ b/tests/transforms/test_split_non_commuting.py
@@ -1027,6 +1027,27 @@ class TestDifferentiability:
 
         assert qml.math.allclose(actual, [-0.5, np.cos(np.pi / 4)], rtol=0.05)
 
+    @pytest.mark.autograd
+    @pytest.mark.parametrize("grouping_strategy", [None, "default", "qwc", "wires"])
+    def test_non_trainable_obs_autograd(self, grouping_strategy):
+        """Test that we can measure a hamiltonian with non-trainable autograd coefficients."""
+
+        dev = qml.device("default.qubit")
+
+        @partial(split_non_commuting, grouping_strategy=grouping_strategy)
+        @qml.qnode(dev, diff_method="adjoint")
+        def circuit(x):
+            qml.RX(x, 0)
+            c1 = qml.numpy.array(0.1, requires_grad=False)
+            c2 = qml.numpy.array(0.2, requires_grad=False)
+            H = c1 * qml.Z(0) + c2 * qml.X(0)
+            return qml.expval(H)
+
+        x = qml.numpy.array(0.5)
+        actual = qml.grad(circuit)(x)
+
+        assert qml.math.allclose(actual, -0.1 * np.sin(x))
+
     @pytest.mark.jax
     @pytest.mark.parametrize("use_jit", [False, True])
     @pytest.mark.parametrize("grouping_strategy", [None, "default", "qwc", "wires"])