|
| 1 | +# Copyright 2025 D-Wave |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# The use of the discrete autoencoder implementations below (including the |
| 16 | +# DiscreteVariationalAutoencoder) with a quantum computing system is |
| 17 | +# protected by the intellectual property rights of D-Wave Quantum Inc. |
| 18 | +# and its affiliates. |
| 19 | +# |
| 20 | +# The use of the discrete autoencoder implementations below (including the |
| 21 | +# DiscreteVariationalAutoencoder) with D-Wave's quantum computing |
| 22 | +# system will require access to D-Wave’s LeapTM quantum cloud service and |
| 23 | +# will be governed by the Leap Cloud Subscription Agreement available at: |
| 24 | +# https://cloud.dwavesys.com/leap/legal/cloud_subscription_agreement/ |
| 25 | +# |
| 26 | + |
| 27 | +from collections.abc import Callable |
| 28 | +from typing import Optional |
| 29 | + |
| 30 | +import torch |
| 31 | + |
| 32 | +__all__ = ["DiscreteVariationalAutoencoder"] |
| 33 | + |
| 34 | + |
| 35 | +class DiscreteVariationalAutoencoder(torch.nn.Module): |
| 36 | + """DiscreteAutoEncoder architecture amenable for training discrete models as priors. |
| 37 | + See https://iopscience.iop.org/article/10.1088/2632-2153/aba220 |
| 38 | +
|
| 39 | + Such discrete models include spin-variable models amenable for the QPU. This |
| 40 | + architecture is a modification of the standard autoencoder architecture, where |
| 41 | + the encoder outputs a latent representation of the data, and the decoder |
| 42 | + reconstructs the data from the latent representation. In our case, there is an |
| 43 | + additional step where the latent representation is mapped to a discrete |
| 44 | + representation, which is then passed to the decoder. |
| 45 | +
|
| 46 | + Args: |
| 47 | + encoder (torch.nn.Module): The encoder must output latents that are later on |
| 48 | + passed to ``latent_to_discrete``. An encoder has signature (x) -> l. x has |
| 49 | + shape (batch_size, f1, f2, ...) and l has shape (batch_size, l1, l2, ...). |
| 50 | + decoder (torch.nn.Module): Decodes discrete tensors into data tensors. A decoder |
| 51 | + has signature (d) -> x'. d has shape (batch_size, n, d1, d2, ...) and x' has |
| 52 | + shape (batch_size, f'1, f'2, ...); if x' is the reconstructed data then |
| 53 | + fi=f'i, but x' might be another representation of the data (e.g. in a |
| 54 | + text-to-image model, x is a sequence of tokens, and x' is an image). Note |
| 55 | + that the decoder input is of shape (batch_size, n, d1, d2, ...), where n is |
| 56 | + a number of discrete representations to be created from a single latent |
| 57 | + representation of a single initial data point. |
| 58 | + latent_to_discrete (Callable[[torch.Tensor, int], torch.Tensor] | None): A |
| 59 | + stochastic and differentiable function that maps the output of the encoder |
| 60 | + to a discrete representation (a function is deterministic by definition; |
| 61 | + here "stochastic" means the function implicitly takes an additional noise |
| 62 | + variables as input). Importantly, since the function is stochastic, it |
| 63 | + allows for the creation of multiple discrete representations from the latent |
| 64 | + representation of a single data point. Thus, the signature of this function |
| 65 | + is (l, n) -> d, where l is the output of the encoder and has shape |
| 66 | + (batch_size, l1, l2, ...), n is the number of discrete representations per |
| 67 | + data point, and d has shape (batch_size, n, d1, d2, ...), which will be the |
| 68 | + input to the decoder. If None, the gumbel softmax function is used for |
| 69 | + stochasticity. Defaults to None. |
| 70 | + """ |
| 71 | + |
| 72 | + def __init__( |
| 73 | + self, |
| 74 | + encoder: torch.nn.Module, |
| 75 | + decoder: torch.nn.Module, |
| 76 | + latent_to_discrete: Optional[Callable[[torch.Tensor, int], torch.Tensor]] = None, |
| 77 | + ): |
| 78 | + super().__init__() |
| 79 | + self._encoder = encoder |
| 80 | + self._decoder = decoder |
| 81 | + if latent_to_discrete is None: |
| 82 | + |
| 83 | + def latent_to_discrete( |
| 84 | + logits: torch.Tensor, n_samples: int |
| 85 | + ) -> torch.Tensor: |
| 86 | + # Logits is of shape (batch_size, n_discrete), we assume these logits |
| 87 | + # refer to the probability of each discrete variable being 1. To use the |
| 88 | + # gumbel softmax function we need to reshape the logits to (batch_size, |
| 89 | + # n_discrete, 1), and then stack the logits to a zeros tensor of the |
| 90 | + # same shape. This is done to ensure that the gumbel softmax function |
| 91 | + # works correctly. |
| 92 | + |
| 93 | + logits = logits.unsqueeze(-1) |
| 94 | + logits = torch.cat((logits, torch.zeros_like(logits)), dim=-1) |
| 95 | + # We now create a new leading dimension and repeat the logits n_samples |
| 96 | + # times: |
| 97 | + logits = logits.unsqueeze(1).repeat(1, n_samples, 1, 1) |
| 98 | + one_hots = torch.nn.functional.gumbel_softmax( |
| 99 | + logits, tau=1 / 7, hard=True |
| 100 | + ) |
| 101 | + # The constant 1/7 is used because it was used in |
| 102 | + # https://iopscience.iop.org/article/10.1088/2632-2153/aba220 |
| 103 | + |
| 104 | + # one_hots is of shape (batch_size, n_samples, n_discrete, 2), we need |
| 105 | + # to take the first element of the last dimension and convert it to spin |
| 106 | + # variables to make the latent space compatible with QPU models. |
| 107 | + return one_hots[..., 0] * 2 - 1 |
| 108 | + |
| 109 | + self._latent_to_discrete = latent_to_discrete |
| 110 | + |
| 111 | + @property |
| 112 | + def encoder(self): |
| 113 | + """Encoder network that maps image data to latent spinstrings.""" |
| 114 | + return self._encoder |
| 115 | + |
| 116 | + @property |
| 117 | + def decoder(self): |
| 118 | + """Decoder network that maps latent variables to images.""" |
| 119 | + return self._decoder |
| 120 | + |
| 121 | + @property |
| 122 | + def latent_to_discrete(self): |
| 123 | + """Function that maps the output of the encoder to a discrete representation""" |
| 124 | + return self._latent_to_discrete |
| 125 | + |
| 126 | + def forward( |
| 127 | + self, x: torch.Tensor, n_samples: int = 1 |
| 128 | + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: |
| 129 | + """Ingests data into the :class:`DiscreteVariationalAutoencoder`. |
| 130 | +
|
| 131 | + Args: |
| 132 | + x (torch.Tensor): Input data of shape (batch_size, ...). |
| 133 | + n_samples (int, optional): Since the ``latent_to_discrete`` map is, in |
| 134 | + general, stochastic (see :class:`DiscreteVariationalAutoencoder` for more on this), |
| 135 | + several different discrete samples can be obtained by applying this map |
| 136 | + to the same encoded data point. This argument specifies how many such |
| 137 | + samples are obtained. Defaults to 1. |
| 138 | +
|
| 139 | + Returns: |
| 140 | + tuple[torch.Tensor, torch.Tensor, torch.Tensor]: The reconstructed data of |
| 141 | + shape (batch_size, n_samples, ...), the discrete representation(s) of the |
| 142 | + encoded data with the shape (batch_size, n_samples, ...), and the logits, |
| 143 | + which are the encoded data of shape (batch_size, ...). |
| 144 | + """ |
| 145 | + latents = self.encoder(x) |
| 146 | + discretes = self.latent_to_discrete(latents, n_samples) |
| 147 | + xhat = self.decoder(discretes) |
| 148 | + return latents, discretes, xhat |
0 commit comments