import numpy as np
import torch
import torch.nn as nn
from numpy import ndarray
from torch import Tensor
from rl_saloon.agents.bandits.bandit_configuration import ContextualBanditConfiguration
from rl_saloon.agents.bandits.contextual.sampling.sampling_algorithm import SamplingAlgorithm
from rl_saloon.agents.bandits.contextual.sampling.with_policy_action_probabilities import WithPolicyActionProbabilities
from rl_saloon.utils.hyperparameters.with_hyperparameters import WithHyperparameters
from rl_saloon.utils.parameters.parameters import NeuralThompsonSamplingParameters
from rl_saloon.utils.states_and_actions.action import Action, DiscreteAction
from rl_saloon.utils.states_and_actions.encoders.encoder_factory import EncoderFactory
from rl_saloon.utils.states_and_actions.iterators.discrete_action_iterator import DiscreteActionIterator
from rl_saloon.utils.states_and_actions.state import State
class NeuralThompsonSamplingNetwork(nn.Module):
"""
Neural network for the neural Thompson sampling algorithm. It is a simple feed-forward neural network with ReLU
activation functions.
code
Attributes
----------
regularisation_parameter: float
The strength of the L2 regularisation.
use_bias: bool
Whether to use bias terms in the neural network.
network_width: int
The number of hidden units in the neural network. The hidden layers are all of the same size.
weights: List[Tensor]
The weights of the neural network.
biases: List[Tensor]
The biases of the neural network.
Methods
-------
forward(x: Tensor) -> Tensor
Returns the output of the neural network for the given input.
get_loss(x: Tensor, y: Tensor, initial_weights: List[Tensor) -> Tensor
Returns the loss of the neural network for the given input, output and the initial weights. The loss is the mean
squared error plus the L2 regularisation term.
_get_l2_regularisation(initial_weights: List[Tensor]) -> Tensor
Returns the L2 regularisation term centered at the initial network weights multiplied by the regularisation
parameter and the network width.
get_flatten_network_gradients(x: Tensor) -> List[Tensor]
Returns the flattened gradients of the network output with respect to the weights.
References
----------
ZHANG, Weitong, et al. "Neural Thompson Sampling." International Conference on Learning Representations. 2020.
https://arxiv.org/pdf/2010.00827.pdf
"""
def __init__(self, regularisation_parameter: float,
use_bias: bool,
weights: Optional[List[Tensor]] = None,
biases: Optional[List[Tensor]] = None) -> None:
super().__init__()
self.regularisation_parameter: float = regularisation_parameter
self.use_bias: bool = use_bias
self._mse_loss = nn.MSELoss()
self._relu = nn.ReLU()
if weights is not None:
self.weights: List[Tensor] = weights
if biases is not None:
if not use_bias:
raise ValueError('Cannot set biases when use_bias is False.')
self.biases: List[Tensor] = biases
@property
def weights(self) -> List[Tensor]:
if not hasattr(self, '_layers'):
return []
return [layer.weight for layer in self._layers]
@property
def biases(self) -> List[Tensor]:
if not hasattr(self, '_layers'):
return []
return [layer.bias for layer in self._layers]
@weights.setter
def weights(self, weights: List[Tensor]) -> None:
if not hasattr(self, '_layers'):
self._layers = nn.ModuleList()
for layer_weights in weights:
self._layers.append(nn.Linear(layer_weights.shape[1], layer_weights.shape[0], bias=self.use_bias))
self._layers[-1].weight = nn.Parameter(layer_weights)
else:
for layer, weight in zip(self._layers, weights):
layer.weight = nn.Parameter(weight)
@biases.setter
def biases(self, biases: List[Tensor]) -> None:
if self.use_bias and all(bias is not None for bias in biases):
if not hasattr(self, '_layers'):
raise ValueError('Cannot set biases before setting weights. '
'Setting biases requires instantiating the network layers with correct dimensions and bias = True first.')
for layer, bias in zip(self._layers, biases):
layer.bias = nn.Parameter(bias)
elif self.use_bias and all(bias is None for bias in biases):
raise ValueError('Cannot set biases to [None, ... ] when use_bias is True.')
elif not self.use_bias and any(bias is not None for bias in biases):
raise ValueError('Cannot set biases when use_bias is False.')
@property
def network_width(self) -> int:
return self._layers[0].weight.shape[0]
def forward(self, x: Tensor) -> Tensor:
for layer in self._layers[:-1]:
x = layer(x)
x = self._relu(x)
return np.sqrt(self.network_width) * self._layers[-1](x)
def get_loss(self, x: Tensor, y: Tensor, initial_weights: List[Tensor],
initial_biases: List[Tensor]) -> Tensor:
return self._mse_loss(self.forward(x), y) + self._get_l2_regularisation(initial_weights, initial_biases)
def _get_l2_regularisation(self, initial_weights: List[Tensor], initial_biases: List[Tensor]) -> Tensor:
diff_tensors = torch.stack([torch.square(layer.weight - init_w.float()).sum()
for layer, init_w in zip(self._layers, initial_weights)])
if self.use_bias:
diff_tensors += torch.stack([torch.square(layer.bias - init_b.float()).sum()
for layer, init_b in zip(self._layers, initial_biases)])
return 0.5 * self.regularisation_parameter * self.network_width * diff_tensors.sum()
def get_flatten_network_gradients(self, x: Tensor) -> List[Tensor]:
flatten_network_gradients: List[Tensor] = []
for row in torch.unbind(x):
row.requires_grad = True
score: Tensor = self.forward(row)
score.backward()
gradients: List[Tensor] = []
for layer in self._layers:
gradients.append(layer.weight.grad.view(-1))
if self.use_bias:
gradients.append(layer.bias.grad.view(-1))
flatten_network_gradients.append(torch.cat(gradients))
return flatten_network_gradients
Assistant
This is a code for the Neural Thompson Sampling (NTS) algorithm implemented in PyTorch. The NTS is a reinforcement learning algorithm which is an extension of the Thompson Sampling algorithm to handle large action spaces and contextual information.
This code defines a class NeuralThompsonSamplingNetwork which is a simple feed-forward neural network with ReLU activation function for the NTS algorithm.
Here is a brief overview of its methods and attributes:
__init__: Initializes the network with the specified parameters (regularisation_parameter, use_bias, weights, biases).
forward: Defines the forward pass of the network.
get_loss: Returns the loss of the network for the given input, output and the initial weights. The loss is the mean squared error plus the L2 regularisation term.
_get_l2_regularisation: Returns the L2 regularisation term centered at the initial network weights multiplied by the regularisation parameter and the network width.
get_flatten_network_gradients: Returns the flattened gradients of the network output with respect to the weights.
This class is used within the context of the NTS algorithm where the neural network is used to model the reward function. The weights and biases of the network are updated based on the observed rewards and the network's predictions. The loss function used is the Mean Squared Error (MSE) plus a regularization term to prevent overfitting.
User
O k but is this type tag
@property
def biases(self) -> List[Tensor]:
if not hasattr(self, '_layers'):
return []
return [layer.bias for layer in self._layers]
correct?
Assistant
Yes, the code appears to be correct and well-formed.
The @property decorator is a way in Python to get the value of a private attribute without any caller programs needing to know that the attribute is being obtained by a method call, essentially turning the method into a getter for a read-only attribute.
In this case, biases is a property of the NeuralThompsonSamplingNetwork class. When you access biases, Python will internally call the biases(self) method to get the biases of all layers in the network.
The method checks if the _layers attribute exists (which should be a list of layers in the network). If _layers does not exist, it returns an empty list. If _layers does exist, it returns a list containing the bias tensor of each layer.
The returned type is List[Tensor], which is a list of PyTorch tensors. Each tensor in the list represents the bias of a layer in the network.
The -> List[Tensor] part is a type hint, indicating that the method returns a list of tensors. This is optional in Python, but it can help with readability and understanding the expected input and output types of a function.