Skip to content

Instantly share code, notes, and snippets.

@thomasahle
Created November 23, 2021 20:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasahle/6e124a4e9b9f4903bf001e37cdeeea65 to your computer and use it in GitHub Desktop.
Save thomasahle/6e124a4e9b9f4903bf001e37cdeeea65 to your computer and use it in GitHub Desktop.
class ParameterDeque(nn.Module):
def __init__(self) -> None:
super(ParameterDeque, self).__init__()
self.left = 0
self.right = 0 # Points at the first non-existing element
def _convert_idx(self, idx):
"""Get the absolute index for the list of modules"""
idx = operator.index(idx)
if not (-len(self) <= idx < len(self)):
raise IndexError('index {} is out of range'.format(idx))
if idx < 0:
idx += len(self)
idx += self.left
return str(idx)
def __getitem__(self, idx):
return self._parameters[self._convert_idx(idx)]
def __setitem__(self, idx: int, param):
self._parameters[self._convert_idx(idx)] = param
def append(self, param):
self._parameters[str(self.right)] = param
self.right += 1
def __len__(self) -> int:
return self.right - self.left
def __iter__(self):
return (self._parameters[i] for i in range(self.left, self.right))
def __delitem__(self, idx):
sidx = self._convert_idx(idx)
if sidx == str(self.left):
self._parameters[sidx] = None
self.left += 1
elif sidx == str(self.right-1):
self.right -= 1
else:
raise IndexError('Can only delete from front and back.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment