cosmiq.gradients#

Gradients of a program’s loss, chosen in one place.

g = cq.gradients.estimate(program, loss_fn, method="spsa", shots=2000, samples=50, seed=1)
g.value, g.stderr, g.shots
  • estimate: the selector. “adjoint” and “checkpoint” are exact, through the emulator; “spsa” and “finite-diff” sample, as the hardware would have to; “auto” picks the adjoint, or SPSA in samples-only mode.

  • spsa and finite_diff: the two sampled estimators, for any function of a flat parameter vector (the PennyLane device’s shot mode calls spsa). No parameter-shift rule: an analog block has none.

GradientEstimate

What estimate returns.

Jacobian

What spsa and finite_diff return.

estimate

\(\partial\,\mathrm{loss}/\partial\theta\), where loss = loss_fn(emulator.run(program(*inputs), ...)) is a scalar and \(\theta\) are the program's parameters that require grad.

finite_diff

Finite differences of fn along every axis of theta, a step of step: central (2 calls a value), or, where a step would cross a limit in low or high ([P], \(\pm\infty\) for none), second-order one-sided and anchored at theta (2 calls a value, plus one at theta).

spsa

SPSA's estimate of \(\partial\,\mathrm{fn}/\partial\,\mathrm{theta}\), from samples random directions.

Method

Classes

class cosmiq.gradients.GradientEstimate(value: Mapping[str, Tensor], stderr: Mapping[str, Tensor] | None, shots: int, evaluations: int, method: str)#

Bases: object

What estimate returns.

value: Mapping[str, Tensor]#

\(\partial\,\mathrm{loss}/\partial\theta\) by name (named_parameters, the ones that require grad), shaped like \(\theta\), float64.

stderr: Mapping[str, Tensor] | None#

The standard error of each value, same shapes; None for the exact methods. Zeros when finite differences ran on exact values; NaN when it can’t be told (one SPSA direction, or finite differences of sampled values with samples=1).

shots: int#

Shots used in all, over every run and batch row; 0 when nothing was sampled.

evaluations: int#

Emulator runs.

method: str#

The method used, “auto” resolved: “spsa”, or the mode the engine’s gradient took, “adjoint” or “checkpoint” (both, joined by “+”, when chunks of the batch differed), or “autograd” when the emulator ran method="dense", which autograd differentiates directly.

class cosmiq.gradients.Jacobian(value: Tensor, stderr: Tensor | None, evaluations: int)#

Bases: object

What spsa and finite_diff return.

value: Tensor#

[*out, P]: \(\partial\,\mathrm{fn}/\partial\,\mathrm{theta}\), float64.

stderr: Tensor | None#

Same shape: SPSA’s standard error, the spread of its samples (0 when they can’t vary, NaN with one sample; never the bias). None from finite_diff, whose single evaluation per point can’t tell whether fn is noisy.

evaluations: int#

Calls of fn.

Functions

cosmiq.gradients.estimate(program: AnalogProgram, loss_fn: Callable[[EmulationResult], Tensor | float], *, inputs: Sequence[Any] = (), method: Literal['auto', 'adjoint', 'checkpoint', 'spsa', 'finite-diff'] = 'auto', emulator: Emulator | RemoteSession | LocalSession | None = None, shots: int | None = None, samples: int | None = None, step: float | None = None, noise: Literal['device', 'hardware'] | NoiseModel | None = None, seed: int | None = None) → GradientEstimate#

\(\partial\,\mathrm{loss}/\partial\theta\), where loss = loss_fn(emulator.run(program(*inputs), ...)) is a scalar and \(\theta\) are the program’s parameters that require grad.

  • method:

    • “adjoint” and “checkpoint”: exact, from one run of a copy of emulator with that gradient= (the caller’s emulator is never changed); loss_fn must keep its graph.

    • “spsa”: samples random directions (default 20), steps of step (default 0.1), two runs each. “finite-diff”: central differences along every value of \(\theta\), steps of step (default 0.05), two runs each, repeated samples times (default 1).

    • “auto”: “spsa” when emulator.samples_only. Otherwise the emulator’s own choice (gradient="auto"): the adjoint, falling back to checkpointing when its certificate fails; method in the result says which ran. “adjoint” and “checkpoint” are strict.

  • The sampled methods step the raw parameters, so a sigmoid-mode bounded value can’t leave its limits. A clamp-mode value whose step would cross a limit takes a second-order one-sided difference anchored at its value, pointing inside (bias \(-h^2/3 \cdot \partial^3 f\); two steps must fit inside), and SPSA holds it still in its random steps (spsa, finite_diff).

  • shots: run in shot mode, for a loss_fn that reads result.shots (samples-only mode needs it). For the sampled methods only.

  • noise: as in Emulator.run. With noise, the run keeps no state, so loss_fn reads the emulator’s observable or the shots.

  • seed: the root of every seed: the directions and each run’s draws, which are all different, as the hardware’s would be. None draws one from torch’s generator.

  • emulator may be a cq.remote session: the runs go to its box with its emulator’s options (see the module docstring); loss_fn then reads the observable or the shots, since remote runs keep no state.

cosmiq.gradients.finite_diff(fn: Callable[[Tensor], Tensor], theta: Tensor, *, step: float = FD_STEP, low: Tensor | None = None, high: Tensor | None = None) → Jacobian#

Finite differences of fn along every axis of theta, a step of step: central (2 calls a value), or, where a step would cross a limit in low or high ([P], \(\pm\infty\) for none), second-order one-sided and anchored at theta (2 calls a value, plus one at theta). fn takes a detached float64 [P] tensor and returns a float64 [*out] one.

cosmiq.gradients.spsa(fn: Callable[[Tensor], Tensor], theta: Tensor, *, samples: int = SPSA_SAMPLES, step: float = SPSA_STEP, seed: int | None = None, low: Tensor | None = None, high: Tensor | None = None) → Jacobian#

SPSA’s estimate of \(\partial\,\mathrm{fn}/\partial\,\mathrm{theta}\), from samples random directions.

fn takes a detached float64 [P] tensor and returns a float64 [*out] tensor, which may be a shot-noise estimate. step is c, the size of each step along every axis. seed draws the directions (None: from torch’s generator); fn’s own randomness is its business. low and high are [P] limits (\(\pm\infty\) for none): a value whose step would cross one takes a one-sided difference anchored at theta instead (see the module docstring).

Values

cosmiq.gradients.Method#

alias of Literal[‘auto’, ‘adjoint’, ‘checkpoint’, ‘spsa’, ‘finite-diff’]