|
| 1 | +import tensorflow as tf |
| 2 | +from tensorflow.keras.layers import Layer # type: ignore |
| 3 | +from tensorflow.keras import activations |
| 4 | +from tensorflow.keras import initializers |
| 5 | +from typing import List, Optional, Text, Tuple |
| 6 | +import tensornetwork as tn |
| 7 | +from tensornetwork.network_components import Node |
| 8 | +import numpy as np |
| 9 | +import math |
| 10 | + |
| 11 | + |
| 12 | +@tf.keras.utils.register_keras_serializable() # type: ignore |
| 13 | + # package='tensornetwork', name='dense_mpo') |
| 14 | +class DenseMPO(Layer): |
| 15 | + """Matrix Product Operator (MPO) TN layer. |
| 16 | +
|
| 17 | + Example: |
| 18 | +
|
| 19 | + ```python |
| 20 | + # as first layer in a sequential model: |
| 21 | + model = Sequential() |
| 22 | + model.add( |
| 23 | + DenseMPO(1024, num_nodes=4, bond_dim=8, activation='relu', |
| 24 | + input_shape=(1024,))) |
| 25 | + # now the model will take as input arrays of shape (*, 1024) |
| 26 | + # and output arrays of shape (*, 1024). |
| 27 | + # After the first layer, you don't need to specify |
| 28 | + # the size of the input anymore: |
| 29 | + model.add(DenseMPO(1024, num_nodes=4, bond_dim=8, activation='relu')) |
| 30 | + ``` |
| 31 | +
|
| 32 | + Args: |
| 33 | + output_dim: Positive integer, dimensionality of the output space. |
| 34 | + num_nodes: Positive integer, number of nodes in the MPO. |
| 35 | + Note input_shape[-1]**(1. / num_nodes) and output_dim**(1. / num_nodes) |
| 36 | + must both be round. |
| 37 | + bond_dim: Positive integer, size of the intermediate dimension. |
| 38 | + activation: Activation function to use. |
| 39 | + If you don't specify anything, no activation is applied |
| 40 | + (ie. "linear" activation: `a(x) = x`). |
| 41 | + use_bias: Boolean, whether the layer uses a bias vector. |
| 42 | + kernel_initializer: Initializer for the node weight matrices. |
| 43 | + bias_initializer: Initializer for the bias vector. |
| 44 | +
|
| 45 | + Input shape: |
| 46 | + 2D tensor with shape: `(batch_size, input_shape[-1])`. |
| 47 | +
|
| 48 | + Output shape: |
| 49 | + 2D tensor with shape: `(batch_size, output_dim)`. |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__(self, |
| 53 | + output_dim: int, |
| 54 | + num_nodes: int, |
| 55 | + bond_dim: int, |
| 56 | + use_bias: Optional[bool] = True, |
| 57 | + activation: Optional[Text] = None, |
| 58 | + kernel_initializer: Optional[Text] = 'glorot_uniform', |
| 59 | + bias_initializer: Optional[Text] = 'zeros', |
| 60 | + **kwargs) -> None: |
| 61 | + |
| 62 | + # Allow specification of input_dim instead of input_shape, |
| 63 | + # for compatability with Keras layers that support this |
| 64 | + if 'input_shape' not in kwargs and 'input_dim' in kwargs: |
| 65 | + kwargs['input_shape'] = (kwargs.pop('input_dim'),) |
| 66 | + |
| 67 | + assert num_nodes > 2, 'Need at least 2 nodes to create MPO' |
| 68 | + |
| 69 | + super(DenseMPO, self).__init__(**kwargs) |
| 70 | + |
| 71 | + self.output_dim = output_dim |
| 72 | + self.num_nodes = num_nodes |
| 73 | + self.bond_dim = bond_dim |
| 74 | + self.nodes = [] |
| 75 | + self.use_bias = use_bias |
| 76 | + self.activation = activations.get(activation) |
| 77 | + self.kernel_initializer = initializers.get(kernel_initializer) |
| 78 | + self.bias_initializer = initializers.get(bias_initializer) |
| 79 | + |
| 80 | + def build(self, input_shape: List[int]) -> None: |
| 81 | + # Disable the attribute-defined-outside-init violations in this function |
| 82 | + # pylint: disable=attribute-defined-outside-init |
| 83 | + if input_shape[-1] is None: |
| 84 | + raise ValueError('The last dimension of the inputs to `Dense` ' |
| 85 | + 'should be defined. Found `None`.') |
| 86 | + |
| 87 | + def is_perfect_root(n, n_nodes): |
| 88 | + root = n**(1. / n_nodes) |
| 89 | + return round(root)**n_nodes == n |
| 90 | + |
| 91 | + # Ensure the MPO dimensions will work |
| 92 | + assert is_perfect_root(input_shape[-1], self.num_nodes), \ |
| 93 | + f'Input dim incorrect.\ |
| 94 | + {input_shape[-1]}**(1. / {self.num_nodes}) must be round.' |
| 95 | + |
| 96 | + assert is_perfect_root(self.output_dim, self.num_nodes), \ |
| 97 | + f'Output dim incorrect. \ |
| 98 | + {self.output_dim}**(1. / {self.num_nodes}) must be round.' |
| 99 | + |
| 100 | + super(DenseMPO, self).build(input_shape) |
| 101 | + |
| 102 | + self.in_leg_dim = math.ceil(input_shape[-1]**(1. / self.num_nodes)) |
| 103 | + self.out_leg_dim = math.ceil(self.output_dim**(1. / self.num_nodes)) |
| 104 | + |
| 105 | + self.nodes.append( |
| 106 | + self.add_weight(name='end_node_first', |
| 107 | + shape=(self.in_leg_dim, self.bond_dim, |
| 108 | + self.out_leg_dim), |
| 109 | + trainable=True, |
| 110 | + initializer=self.kernel_initializer)) |
| 111 | + for i in range(self.num_nodes - 2): |
| 112 | + self.nodes.append( |
| 113 | + self.add_weight(name=f'middle_node_{i}', |
| 114 | + shape=(self.in_leg_dim, self.bond_dim, self.bond_dim, |
| 115 | + self.out_leg_dim), |
| 116 | + trainable=True, |
| 117 | + initializer=self.kernel_initializer)) |
| 118 | + self.nodes.append( |
| 119 | + self.add_weight(name='end_node_last', |
| 120 | + shape=(self.in_leg_dim, self.bond_dim, |
| 121 | + self.out_leg_dim), |
| 122 | + trainable=True, |
| 123 | + initializer=self.kernel_initializer)) |
| 124 | + |
| 125 | + self.bias_var = self.add_weight( |
| 126 | + name='bias', |
| 127 | + shape=(self.output_dim,), |
| 128 | + trainable=True, |
| 129 | + initializer=self.bias_initializer) if self.use_bias else None |
| 130 | + |
| 131 | + def call(self, inputs: tf.Tensor, **kwargs) -> tf.Tensor: # pylint: disable=unused-argument |
| 132 | + |
| 133 | + |
| 134 | + def f(x: tf.Tensor, nodes: List[Node], num_nodes: int, in_leg_dim: int, |
| 135 | + use_bias: bool, bias_var: tf.Tensor) -> tf.Tensor: |
| 136 | + orig_shape = x.shape |
| 137 | + l = [in_leg_dim] * num_nodes |
| 138 | + input_reshaped = tf.reshape(x, tuple(l)) |
| 139 | + x_node = tn.Node(input_reshaped, name='xnode', backend="tensorflow") |
| 140 | + |
| 141 | + tn_nodes = [] |
| 142 | + for i, v in enumerate(nodes): |
| 143 | + tn_nodes.append(tn.Node(v, name=f'node_{i}', backend="tensorflow")) |
| 144 | + # Connect every node to input node |
| 145 | + x_node[i] ^ tn_nodes[i][0] |
| 146 | + |
| 147 | + # Connect all core nodes |
| 148 | + tn_nodes[0][1] ^ tn_nodes[1][1] |
| 149 | + for i, _ in enumerate(tn_nodes): |
| 150 | + if len(tn_nodes[i].shape) == 4: |
| 151 | + tn_nodes[i][2] ^ tn_nodes[i + 1][1] |
| 152 | + |
| 153 | + # The TN should now look like this |
| 154 | + # | | | |
| 155 | + # 1 --- 2 --- ... |
| 156 | + # \ / / |
| 157 | + # x |
| 158 | + |
| 159 | + # Contract TN using zipper algorithm |
| 160 | + temp = x_node @ tn_nodes[0] |
| 161 | + for i in range(1, len(tn_nodes)): |
| 162 | + temp = temp @ tn_nodes[i] |
| 163 | + |
| 164 | + result = tf.reshape(temp.tensor, orig_shape) |
| 165 | + if use_bias: |
| 166 | + result += bias_var |
| 167 | + |
| 168 | + return result |
| 169 | + |
| 170 | + result = tf.vectorized_map( |
| 171 | + lambda vec: f(vec, self.nodes, self.num_nodes, self.in_leg_dim, self. |
| 172 | + use_bias, self.bias_var), inputs) |
| 173 | + if self.activation is not None: |
| 174 | + result = self.activation(result) |
| 175 | + return tf.reshape(result, (-1, self.output_dim)) |
| 176 | + |
| 177 | + def compute_output_shape(self, input_shape: List[int]) -> Tuple[int, int]: |
| 178 | + return (input_shape[0], self.output_dim) |
| 179 | + |
| 180 | + def get_config(self) -> dict: |
| 181 | + """Returns the config of the layer. |
| 182 | +
|
| 183 | + The same layer can be reinstantiated later |
| 184 | + (without its trained weights) from this configuration. |
| 185 | +
|
| 186 | + Returns: |
| 187 | + Python dictionary containing the configuration of the layer. |
| 188 | + """ |
| 189 | + config = {} |
| 190 | + |
| 191 | + # Include the MPO-specific arguments |
| 192 | + mpo_args = ['output_dim', 'num_nodes', 'bond_dim', 'use_bias'] |
| 193 | + for arg in mpo_args: |
| 194 | + config[arg] = getattr(self, arg) |
| 195 | + |
| 196 | + # Serialize the activation |
| 197 | + config['activation'] = activations.serialize(getattr(self, 'activation')) |
| 198 | + |
| 199 | + # Serialize the initializers |
| 200 | + mpo_initializers = ['kernel_initializer', 'bias_initializer'] |
| 201 | + for initializer_arg in mpo_initializers: |
| 202 | + config[initializer_arg] = initializers.serialize( |
| 203 | + getattr(self, initializer_arg)) |
| 204 | + |
| 205 | + # Get base config |
| 206 | + base_config = super(DenseMPO, self).get_config() |
| 207 | + return dict(list(base_config.items()) + list(config.items())) |
0 commit comments