|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from collections import deque
|
|
|
|
import torch
|
|
from torch import nn
|
|
|
|
|
|
def populate_queues(
|
|
queues: dict[str, deque], batch: dict[str, torch.Tensor], exclude_keys: list[str] | None = None
|
|
):
|
|
if exclude_keys is None:
|
|
exclude_keys = []
|
|
for key in batch:
|
|
|
|
|
|
if key not in queues or key in exclude_keys:
|
|
continue
|
|
if len(queues[key]) != queues[key].maxlen:
|
|
|
|
while len(queues[key]) != queues[key].maxlen:
|
|
queues[key].append(batch[key])
|
|
else:
|
|
|
|
queues[key].append(batch[key])
|
|
return queues
|
|
|
|
|
|
def get_device_from_parameters(module: nn.Module) -> torch.device:
|
|
"""Get a module's device by checking one of its parameters.
|
|
|
|
Note: assumes that all parameters have the same device
|
|
"""
|
|
return next(iter(module.parameters())).device
|
|
|
|
|
|
def get_dtype_from_parameters(module: nn.Module) -> torch.dtype:
|
|
"""Get a module's parameter dtype by checking one of its parameters.
|
|
|
|
Note: assumes that all parameters have the same dtype.
|
|
"""
|
|
return next(iter(module.parameters())).dtype
|
|
|
|
|
|
def get_output_shape(module: nn.Module, input_shape: tuple) -> tuple:
|
|
"""
|
|
Calculates the output shape of a PyTorch module given an input shape.
|
|
|
|
Args:
|
|
module (nn.Module): a PyTorch module
|
|
input_shape (tuple): A tuple representing the input shape, e.g., (batch_size, channels, height, width)
|
|
|
|
Returns:
|
|
tuple: The output shape of the module.
|
|
"""
|
|
dummy_input = torch.zeros(size=input_shape)
|
|
with torch.inference_mode():
|
|
output = module(dummy_input)
|
|
return tuple(output.shape)
|
|
|