ThreadSafeModel
ThreadSafeModel(learner_model: torch.nn.Module, device: torch.device)A thread-safe container around any nn.Module that manages locking and synchronization. Uses explicit method forwarding instead of getattr for better clarity and IDE support.
Initialize the ThreadSafeModel container.
Parameters:
learner_model(Module) – The underlying model.device(device) – The device the model is on.
Properties
model
model: torch.nn.ModuleGet the underlying model.
Returns:
Module– The wrapped nn.Module.
Methods
get_lock
get_lock() -> threading.LockGet the lock for manual synchronization. Use with caution.
Returns:
Lock– The threading.Lock instance.
get_q_values
get_q_values(x: torch.Tensor) -> torch.TensorCompute Q-values for the given input states.
Delegates to the underlying model's get_q_values method. Only works if the underlying model has a get_q_values() method.
Parameters:
x(Tensor) – The input tensor of shape (batch, *observation_shape).
Returns:
Tensor– Q-values of shape (batch, actions).
Raises:
AttributeError– If the underlying model does not have aget_q_values()method.
get_state_dict
get_state_dict(reset_event: bool = False, to_cpu: bool = True) -> dict[str, torch.Tensor]Retrieve the model's state dictionary safely.
Parameters:
reset_event(bool) – Whether to reset the updated event after retrieving the state.to_cpu(bool) – Whether to move the state dictionary tensors to the CPU.
Returns:
dict[str, Tensor]– The model's state dictionary.
is_updated_event_set
is_updated_event_set() -> boolCheck if the model has been updated since the last event reset.
Returns:
bool– True if the updated event is set, False otherwise.
parameters
parameters() -> Iterator[torch.nn.Parameter]Get the parameters of the underlying model.
Returns:
Iterator[Parameter]– Iterator over model parameters.
perform_update
perform_update(optimizer: torch.optim.Optimizer, loss: torch.Tensor) -> NonePerform an optimization step safely under the lock and set the updated event.
Parameters:
optimizer(Optimizer) – The optimizer to use.loss(Tensor) – The loss to backpropagate.
reset_noise
reset_noise() -> NoneReset noise for all noisy layers in the model.
Thread-safe: acquires the lock to prevent concurrent reads during noise reset. Only works if the underlying model has a reset_noise() method.
set_updated_event
set_updated_event() -> NoneSet the updated event to signal that the model has been updated.
sync_to
sync_to(target_model: torch.nn.Module) -> NoneSynchronise the target model with the learner model's current weights safely.
Parameters:
target_model(Module) – The model to synchronise.