التدرج بقاعدة إزاحة المعامل في PennyLane
Parameter-Shift Gradient in PennyLane
حساب مشتقة $f(\theta)=\langle Z\rangle=\cos\theta$ بعد $R_X(\theta)$ بقاعدة إزاحة المعامل، ومقارنتها بالحساب اليدوي والقيمة التحليلية $-\sin\theta$.
Differentiate f(θ) = ⟨Z⟩ = cos θ after R_X(θ) with the parameter-shift rule; compare with a manual shift and the analytic −sin θ.
لبوابة على الصورة $e^{-i\theta P/2}$ مع $P$ مؤثر باولي، تصح القاعدة الدقيقة $$\frac{\partial f}{\partial\theta}=\frac{f(\theta+\pi/2)-f(\theta-\pi/2)}{2}.$$ ليست تقريباً بالفروق المنتهية، بل مساواة تامة؛ لذلك يمكن استخدامها على العتاد بتقييم الدائرة مرتين لكل معامل. diff_method="parameter-shift" يطلب هذه الطريقة صراحة.
المتطلبات: pip install pennylane. تُشغَّل الشيفرة على جهازك أو في Colab، لا داخل ووردبريس.
الشيفرة
import pennylane as qml
from pennylane import numpy as np
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev, diff_method="parameter-shift")
def f(theta):
qml.RX(theta, wires=0)
return qml.expval(qml.PauliZ(0))
theta = np.array(0.7, requires_grad=True)
grad = qml.grad(f)(theta)
manual = (f(theta + np.pi / 2) - f(theta - np.pi / 2)) / 2
print("f(theta) =", round(float(f(theta)), 6), "| cos(theta) =", round(float(np.cos(theta)), 6))
print("parameter-shift grad =", round(float(grad), 6))
print("manual shift =", round(float(manual), 6))
print("analytic -sin(theta) =", round(float(-np.sin(theta)), 6))
شرح الشيفرة سطراً بسطر
| السطر | الشرح |
|---|---|
| 1-2 | الاستيراد. |
| 4 | جهاز بكيوبت واحد. |
| 7 | عقدة كمّية تستخدم إزاحة المعامل للاشتقاق. |
| 8-10 | الدالة: RX(θ) ثم ⟨Z⟩ = cos θ. |
| 13 | معامل قابل للاشتقاق. |
| 14 | التدرج من PennyLane. |
| 15 | التدرج يدوياً بإزاحتين ±π/2. |
| 16 | مقارنة f بالقيمة cos θ. |
| 17-19 | طباعة التدرجات الثلاثة. |
المخرجات المتوقعة (من تشغيل فعلي)
f(theta) = 0.764842 | cos(theta) = 0.764842 parameter-shift grad = -0.644218 manual shift = -0.644218 analytic -sin(theta) = -0.644218
الناتج حتمي (جهاز دقيق دون لقطات).
جرّب بنفسك
موضوعات مرتبطة
المراجع
- K. Mitarai; M. Negoro; M. Kitagawa; K. Fujii (2018). Quantum circuit learning. Phys. Rev. A 98:032309 doi:10.1103/PhysRevA.98.032309
- Xanadu (2025). Parameter-shift rules. PennyLane Glossary pennylane.ai
- Xanadu (2025). PennyLane Documentation. PennyLane docs.pennylane.ai
