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
Here are a few suggestions to improve the NeuralThompsonSamplingNetwork class:
Add type annotations for the methods and properties. This will make the code more self-documenting and help catch bugs.
Use PyTorch's built-in regularization functions like nn.MSELoss(reduction='sum') instead of manually computing the L2 regularization loss. This will be more efficient and easier to understand.
Consider making the network construction more flexible by taking the layer sizes and activations as arguments rather than hardcoding a specific network architecture.
The get_flatten_network_gradients() method could be simplified by using PyTorch autograd instead of manually computing gradients.
Add documentation for the public methods and properties. Comments explain what the code does, docstrings explain how to use it.
Use more descriptive variable names like layer_weights instead of just weights.
Validate arguments passed to methods - check for correct shapes and values.
Add unit tests to validate the network computations and catch bugs.
Here is an example of the forward pass with some of these suggestions applied:
python
def forward(self, inputs: Tensor) -> Tensor:
"""Forward pass through the network"""
x = inputs
for layer in self._layers[:-1]:
x = layer(x)
x = self._activation_fn(x)
return self._output_scaling * self._layers[-1](x)
I hope these tips help improve the code! Let me know if any part needs more clarification.
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 type annotation for the biases property is correct.
By annotating it as:
python
@property
def biases(self) -> List[Tensor]:
It indicates that:
This is a property, not a regular method
The return type of accessing this property is List[Tensor]
So that means anytime you access self.biases, it is expected to return a list of PyTorch Tensor objects.
The body of the property returns exactly that - a list comprehension that extracts the bias attribute from each layer, which will be a Tensor.
So the type annotation accurately captures the expected return type. This helps catch bugs if you ever accidentally change the implementation to return something else besides a list of Tensors.
The only thing I might change is to use a more precise type annotation like:
python
@property
def biases(self) -> List[nn.Parameter]:
Since specifically it returns the bias Parameters of each layer. But the current List[Tensor] works fine too.
So in summary - yes the type annotation looks correct! Let me know if any other part is unclear!