Temporal coding enables hyperacuity in event-based vision.
The 8 matches
- [1] § Methods › Model implementation and training details ↔ eb_models.py, lines 523–557 · score 0.87 · residual connections, layer normalization, multi head, dropout rate, Transformer layers, query
- [2] § Methods › Model implementation and training details ↔ losses.py, lines 11–49 · score 0.67 · Cross Entropy, cosine, Temperature, Loss, embedding, logits
- [3] § Methods › Model implementation and training details ↔ eb_models.py, lines 111–251 · score 0.63 · projection head, classification head, logits, batches, dimensional, network
- [4] § Methods › Setup ↔ data_collection/events/syclop_acquire_dataset_20230623.ipynb, lines 552–577 · score 0.62 · TGY D003HV, Maestro, motors, rotations, event
- [5] § Methods › Model implementation and training details ↔ eb_train.py, lines 241–256 · score 0.59 · decay, exponential, Adam, warmup, Optimization, schedule
- [6] § Methods › Model implementation and training details ↔ eb_models.py, lines 289–383 · score 0.54 · GRU layer, classification head, model
- [7] § Methods › Model implementation and training details ↔ eb_contrastive.py, lines 81–127 · score 0.53 · decay, exponential, Adam, schedule, batch, linear
- [8] § Results › Accurate event timing contains task-relevant information ↔ notebooks/fig_acc_vs_jitter_allDS_supp.ipynb, lines 407–454 · score 0.50 · tailed Wilcoxon rank, jitter training, sum, accuracy, EB, event
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Python · 588 lines · 25 KB · other · 3 matches
- import torch
- import torch.nn as nn
- import torch.nn.functional as F
- import torchvision.transforms as transforms
- from torchvision.models import resnet18, ResNet18_Weights
- class TimeSeriesTransformer(nn.Module):
- def __init__(self,
- n_timesteps = 64,
- d_timeseries = 4,
- d_k = 256,
- d_mlp = 512,
- d_mlp2 = 256,
- n_layers = 8,
- num_heads = 4,
- num_classes = 10,
- dropout_rate = 0.1,
- offsets = None,
- scalings = None,
- dropout_ffn_from_layer = 4,
- subseq_len = None,
- model_head = 'cls_mlp',
- model_head_init_method = None,
- input_dense_init_method = None):
- '''
- Transformer for time series data.
- :param n_timesteps: number of timesteps in the input
- :param d_timeseries: dimensionality of the timeseries
- :param d_k: dimensionality of the key and query vectors
- :param d_mlp: dimensionality of the MLP in the feedforward layer
- :param d_mlp2: dimensionality of the MLP in the classification head
- :param n_layers: number of layers in the Transformer
- :param num_heads: number of heads in the Multi-Head Attention
- :param num_classes: number of classes in the classification head
- :param dropout_rate: dropout rate
- :param offsets: offsets to be added to the input
- :param scalings: scalings to be multiplied to the input
- :param dropout_ffn_from_layer: layer from which to apply dropout to the feedforward network
- :param subseq_len: list or tuple. when not None, the input is split into subsequences according to this list, each subsequence is processed by the transformer, and the outputs are concatenated
- :param model_head: head architecture. 'cls_mlp' or 'cls_avgpool'
- Receives input of shape (batch_size, n_timesteps, d_timeseries), returns logits of shape (batch_size, num_classes)
- '''
- super(TimeSeriesTransformer, self).__init__()
- if offsets is None:
- offsets = torch.zeros(1, 1, d_timeseries)
- if scalings is None:
- scalings = torch.ones(1, 1, d_timeseries)
- self.offsets = offsets
- self.scalings = scalings
- self.n_layers = n_layers
- self.dropout_ffn_from_layer = dropout_ffn_from_layer
- self.subseq_len = subseq_len
- self.model_head_init_method = model_head_init_method
- # Initial dense layer to expand dimensions
- #todo: add option to use dedicated input dense layer per subsequence in a case of multiple subsequences
- self.input_dense = nn.Linear(d_timeseries, d_k)
- if input_dense_init_method is not None:
- apply_init_method([self.input_dense], input_dense_init_method)
- # Defining n_layers of Transformer Layers
- self.transformer_layers = nn.ModuleList([
- TransformerLayer(d_k, num_heads, d_mlp, dropout_rate) for _ in range(n_layers)
- ])
- if model_head == 'cls_mlp':
- self.cls_head = ClassifierHead_MLP(d_k * n_timesteps,
- d_mlp2, num_classes, dropout_rate,do_flatten=True)
- elif model_head == 'cls_avgpool':
- self.cls_head = ClassifierHead_AvgPool(d_k, d_mlp2, num_classes, dropout_rate, init_method=model_head_init_method)
- elif model_head == 'proj_avgpool':
- self.cls_head = ProjectionHead_AvgPool(d_k, d_mlp2)
- elif model_head == 'none':
- self.cls_head = nn.Identity()
- else:
- raise ValueError('Unknown cls_head_arch')
- def forward(self, x, attn_mask=None, padding_mask=None):
- # Add offsets and scaling
- #convert to torch tensor locally to avoid problems with multiple GPUs
- torch_offsets = torch.tensor(self.offsets, device=x.device, dtype=x.dtype)
- torch_scalings = torch.tensor(self.scalings, device=x.device, dtype=x.dtype)
- if self.subseq_len is not None and (attn_mask is not None or padding_mask is not None):
- raise ValueError('subseq_len cannot be used with attn_mask or key_padding_mask')
- if self.subseq_len is not None:
- #in a case of multiple subsequences, we create an attention mask to prevent attention between subsequences
- #this mask is a matrix of shape (n_timesteps, n_timesteps) it is false between all pairs of timesteps that belong to different subsequences
- #otherwise, the mask is None
- attn_mask = torch.ones(x.shape[1], x.shape[1], dtype=torch.bool, device=x.device)
- this_position = 0
- for subseq_len in self.subseq_len:
- attn_mask[this_position:this_position+subseq_len, this_position:this_position+subseq_len] = False
- this_position += subseq_len
- x = (x + torch_offsets) * torch_scalings
- x = self.input_dense(x)
- for i, layer in enumerate(self.transformer_layers):
- x = layer(x, apply_dropout=(i >= self.dropout_ffn_from_layer), attn_mask=attn_mask, key_padding_mask=padding_mask)
- x = self.cls_head(x, mask=padding_mask)
- return x
- class TimeSeriesTransformerWithSubseq(nn.Module):
- def __init__(self,
- n_timesteps=64,
- d_timeseries=4,
- d_k=256,
- d_mlp=512,
- d_mlp2=256,
- n_layers=8,
- num_heads=4,
- num_classes=10,
- dropout_rate=0.1,
- offsets=None,
- scalings=None,
- dropout_ffn_from_layer=4,
- subseq_len=None,
- model_head='cls_mlp',
- shared_input_dense=False,
- drop_subseq_prob=0.5,
- extra_dim_for_subsamples=False):
- '''
- Transformer for time series data. With option to split the input into multiple subsequences.
- :param n_timesteps: number of timesteps in the input
- :param d_timeseries: dimensionality of the timeseries
- :param d_k: dimensionality of the key and query vectors
- :param d_mlp: dimensionality of the MLP in the feedforward layer
- :param d_mlp2: dimensionality of the MLP in the classification head
- :param n_layers: number of layers in the Transformer
- :param num_heads: number of heads in the Multi-Head Attention
- :param num_classes: number of classes in the classification head
- :param dropout_rate: dropout rate
- :param offsets: offsets to be added to the input
- :param scalings: scalings to be multiplied to the input
- :param dropout_ffn_from_layer: layer from which to apply dropout to the feedforward network
- :param subseq_len: list or tuple. when not None, the input is split into subsequences according to this list, each subsequence is processed by the transformer, and the outputs are concatenated
- :param model_head: head architecture. 'cls_mlp' or 'cls_avgpool'
- :param shared_input_dense: if True, the input is processed by a single dense layer before being split into subsequences. If False, each subsequence is processed by a dedicated dense layer.
- :param drop_subseq_prob: probability of dropping a subsequence during training
- Receives input of shape (batch_size, n_timesteps, d_timeseries), returns logits of shape (batch_size, num_classes)
- '''
- super(TimeSeriesTransformerWithSubseq, self).__init__()
- if offsets is None:
- offsets = torch.zeros(1, 1, d_timeseries)
- if scalings is None:
- scalings = torch.ones(1, 1, d_timeseries)
- self.offsets = offsets
- self.scalings = scalings
- self.n_layers = n_layers
- self.dropout_ffn_from_layer = dropout_ffn_from_layer
- self.subseq_len = subseq_len
- self.shared_input_dense = shared_input_dense
- self.drop_subseq_prob = drop_subseq_prob
- self.extra_dim_for_subsamples = extra_dim_for_subsamples
- # Initial dense layer to expand dimensions
- if shared_input_dense:
- self.input_dense = nn.Linear(d_timeseries, d_k)
- else:
- self.input_dense = nn.ModuleList([nn.Linear(d_timeseries, d_k) for _ in range(len(subseq_len))])
- if subseq_len is None:
- raise NotImplementedError
- # Defining n_layers of Transformer Layers
- # self.transformer_layers = nn.ModuleList([
- # TransformerLayer(d_k, num_heads, d_mlp, dropout_rate) for _ in range(n_layers)
- # ])
- else:
- # in case of multiple subsequences, we need to split the input into subsequences
- # each subsequence is processed by a dedicated transformer, and the outputs are concatenated
- for i in range(len(subseq_len)):
- setattr(self, 'transformer_stack_{}'.format(i), TransformerCore(d_k=d_k,
- num_heads=num_heads,
- d_mlp=d_mlp,
- n_layers=n_layers,
- dropout_rate=dropout_rate,
- dropout_ffn_from_layer=dropout_ffn_from_layer))
- if model_head == 'cls_mlp':
- self.cls_head = ClassifierHead_MLP(d_k * (len(subseq_len) if subseq_len is not None else 1),
- d_mlp2, num_classes, dropout_rate,do_flatten=extra_dim_for_subsamples)
- elif model_head == 'cls_avgpool':
- self.cls_head = ClassifierHead_AvgPool(d_k, d_mlp2, num_classes, dropout_rate)
- elif model_head == 'proj_avgpool':
- self.cls_head = ProjectionHead_AvgPool(d_k, d_mlp2, skip_mean=True)
- elif model_head == 'none':
- self.cls_head = nn.Identity()
- else:
- raise ValueError('Unknown cls_head_arch')
- def forward(self, x):
- # Add offsets and scaling
- #convert to torch tensor locally to avoid problems with multiple GPUs
- torch_offsets = torch.tensor(self.offsets, device=x.device, dtype=x.dtype)
- torch_scalings = torch.tensor(self.scalings, device=x.device, dtype=x.dtype)
- x = (x + torch_offsets) * torch_scalings
- if self.shared_input_dense:
- x = self.input_dense(x)
- if self.subseq_len is None:
- raise NotImplementedError
- # Pass through each Transformer Layer
- # for i, layer in enumerate(self.transformer_layers):
- # x = layer(x, apply_dropout=(i >= self.dropout_ffn_from_layer))
- else:
- # in case of multiple subsequences, we need to split the input into subsequences
- # each subsequence is processed by a dedicated transformer, and the outputs are passed through average
- # pooling and concatenated
- x_list = []
- this_position = 0
- for i, subseq_len in enumerate(self.subseq_len):
- if self.extra_dim_for_subsamples:
- x_subseq = x[:, i, ...]
- else:
- x_subseq = x[:, this_position:this_position+subseq_len, :]
- this_position += subseq_len
- if not self.shared_input_dense:
- x_subseq = self.input_dense[i](x_subseq)
- x_subseq = getattr(self, 'transformer_stack_{}'.format(i))(x_subseq)
- x_subseq = torch.mean(x_subseq, dim=1)
- x_list.append(x_subseq)
- # if in training mode with probability self.drop_subseq_prob pick at most one subsequence and set it to zero
- # this is done by creating a subsequence of zeros and replacing one random subsequence
- # out of the original subsequences with zeros.
- if self.training:
- if torch.rand(1) < self.drop_subseq_prob:
- x_list[torch.randint(len(x_list),(1,))] = torch.zeros_like(x_list[0])
- #scale all other subsequences to compensate for the zero subsequence
- x_list = [x * (len(x_list) / (len(x_list) - 1)) for x in x_list]
- if self.extra_dim_for_subsamples:
- x = torch.stack(x_list, dim=1)
- else:
- x = torch.cat(x_list, dim=1)
- # Classification head
- x = self.cls_head(x)
- return x
- class TransformerCore(nn.Module):
- def __init__(self,
- d_k=256,
- d_mlp=512,
- n_layers=8,
- num_heads=4,
- dropout_rate=0.1,
- dropout_ffn_from_layer=4):
- '''
- Core of the Transformer. No classification head or input preprocessing.
- :param d_k: dimensionality of the key and query vectors
- :param d_mlp: dimensionality of the MLP in the feedforward layer
- :param n_layers: number of layers in the Transformer
- :param num_heads: number of heads in the Multi-Head Attention
- :param dropout_rate: dropout rate
- :param dropout_ffn_from_layer: layer from which to apply dropout to the feedforward network
- Receives input of shape (batch_size, n_timesteps, d_timeseries), returns logits of shape (batch_size, num_classes)
- '''
- super(TransformerCore, self).__init__()
- self.n_layers = n_layers
- self.dropout_ffn_from_layer = dropout_ffn_from_layer
- # Defining n_layers of Transformer Layers
- self.transformer_layers = nn.ModuleList([
- TransformerLayer(d_k, num_heads, d_mlp, dropout_rate) for _ in range(n_layers)
- ])
- def forward(self, x):
- # Pass through each Transformer Layer
- for i, layer in enumerate(self.transformer_layers):
- x = layer(x, apply_dropout=(i >= self.dropout_ffn_from_layer))
- return x
- class TimeSeriesGRU(nn.Module):
- def __init__(self,
- n_timesteps=64,
- d_timeseries=4,
- d_hidden=256,
- d_mlp=512,
- d_mlp2=256,
- n_layers=8,
- num_classes=10,
- dropout_rate=0.1,
- offsets=None,
- scalings=None,
- dropout_ffn_from_layer=4,
- subseq_len=None,
- model_head='cls_mlp',
- model_head_init_method=None,
- input_dense_init_method=None):
- '''
- GRU-based model for time series data.
- :param n_timesteps: number of timesteps in the input
- :param d_timeseries: dimensionality of the timeseries
- :param d_hidden: dimensionality of the hidden state in the GRU
- :param d_mlp: dimensionality of the MLP in the feedforward layer
- :param d_mlp2: dimensionality of the MLP in the classification head
- :param n_layers: number of GRU layers
- :param num_classes: number of classes in the classification head
- :param dropout_rate: dropout rate
- :param offsets: offsets to be added to the input
- :param scalings: scalings to be multiplied to the input
- :param dropout_ffn_from_layer: layer from which to apply dropout to the feedforward network
- :param subseq_len: list or tuple. when not None, the input is split into subsequences according to this list, each subsequence is processed by the GRU, and the outputs are concatenated
- :param model_head: head architecture. 'cls_mlp' or 'cls_avgpool'
- Receives input of shape (batch_size, n_timesteps, d_timeseries), returns logits of shape (batch_size, num_classes)
- '''
- super(TimeSeriesGRU, self).__init__()
- if offsets is None:
- offsets = torch.zeros(1, 1, d_timeseries)
- if scalings is None:
- scalings = torch.ones(1, 1, d_timeseries)
- self.offsets = offsets
- self.scalings = scalings
- self.n_layers = n_layers
- self.dropout_ffn_from_layer = dropout_ffn_from_layer
- self.subseq_len = subseq_len
- self.model_head_init_method = model_head_init_method
- # Initial dense layer to expand dimensions
- self.input_dense = nn.Linear(d_timeseries, d_hidden)
- if input_dense_init_method is not None:
- apply_init_method([self.input_dense], input_dense_init_method)
- # GRU layer
- self.gru_layers = nn.ModuleList([
- nn.GRU(input_size=d_hidden, hidden_size=d_hidden, num_layers=1, batch_first=True) for _ in range(n_layers)
- ])
- # Dropout layer
- self.dropout = nn.Dropout(dropout_rate)
- # Classification head
- if model_head == 'cls_mlp':
- self.cls_head = ClassifierHead_MLP(d_hidden * n_timesteps, d_mlp2, num_classes, dropout_rate,
- do_flatten=True)
- elif model_head == 'cls_avgpool':
- self.cls_head = ClassifierHead_AvgPool(d_hidden, d_mlp2, num_classes, dropout_rate,
- init_method=model_head_init_method)
- elif model_head == 'proj_avgpool':
- self.cls_head = ProjectionHead_AvgPool(d_hidden, d_mlp2)
- elif model_head == 'none':
- self.cls_head = nn.Identity()
- else:
- raise ValueError('Unknown cls_head_arch')
- def forward(self, x, attn_mask=None, padding_mask=None):
- # Add offsets and scaling
- torch_offsets = torch.tensor(self.offsets, device=x.device, dtype=x.dtype)
- torch_scalings = torch.tensor(self.scalings, device=x.device, dtype=x.dtype)
- if self.subseq_len is not None and (attn_mask is not None or padding_mask is not None):
- raise ValueError('subseq_len cannot be used with attn_mask or key_padding_mask')
- x = (x + torch_offsets) * torch_scalings
- x = self.input_dense(x)
- # GRU forward pass with conditional dropout
- for i, gru_layer in enumerate(self.gru_layers):
- x, _ = gru_layer(x)
- if i >= self.dropout_ffn_from_layer:
- x = self.dropout(x)
- # Apply the classification head
- x = self.cls_head(x.contiguous(), mask=padding_mask)
- return x
- class VanillaCNN(nn.Module):
- def __init__(self, input_shape = (10,10),
- num_classes = 10):
- super(VanillaCNN, self).__init__()
- self.resize = nn.Upsample(size=(56, 56), mode='bilinear', align_corners=False)
- self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
- self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
- self.conv3 = nn.Conv2d(64, 64, kernel_size=2)
- self.pool = nn.MaxPool2d(2)
- # Calculate the size of the flattened features
- self.flat_features = self._get_flat_features()
- self.dropout1 = nn.Dropout(0.3)
- self.fc1 = nn.Linear(self.flat_features, 128)
- self.dropout2 = nn.Dropout(0.3)
- self.fc2 = nn.Linear(128, num_classes)
- def forward(self, x):
- if len(x.shape) == 3:
- x = x.unsqueeze(1)
- x = self.resize(x)
- x = F.relu(self.conv1(x))
- x = self.pool(x)
- x = F.relu(self.conv2(x))
- x = self.pool(x)
- x = F.relu(self.conv3(x))
- x = x.view(-1, self.flat_features)
- x = self.dropout1(x)
- x = F.relu(self.fc1(x))
- x = self.dropout2(x)
- x = self.fc2(x)
- return x
- def _get_flat_features(self):
- # Helper method to calculate the size of the flattened features
- with torch.no_grad():
- x = torch.zeros(1, 1, 56, 56) # Dummy input
- x = F.relu(self.conv1(x))
- x = self.pool(x)
- x = F.relu(self.conv2(x))
- x = self.pool(x)
- x = F.relu(self.conv3(x))
- return x.numel()
- class GrayscaleResNet18(nn.Module):
- def __init__(self, input_shape = (10,10),
- num_classes = 10):
- super(GrayscaleResNet18, self).__init__()
- # Load pretrained ResNet18
- self.resnet = resnet18(weights=None)
- # Modify the first convolutional layer to accept grayscale input
- self.resnet.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
- # Modify the final fully connected layer if needed
- if num_classes != 1000:
- self.resnet.fc = nn.Linear(self.resnet.fc.in_features, num_classes)
- # Define preprocessing transforms
- self.preprocess = transforms.Compose([
- transforms.Resize(224, antialias=True),
- # transforms.CenterCrop(224),
- transforms.Normalize(mean=[0.485], std=[0.229])
- ])
- def forward(self, x):
- # x is expected to be a grayscale image tensor of shape (B, 1, H, W)
- if len(x.shape) == 3:
- x = x.unsqueeze(1)
- x = self.preprocess(x)
- return self.resnet(x)
- class ClassifierHead_MLP(nn.Module):
- def __init__(self, d_flatten, d_mlp, num_classes, dropout_rate, do_flatten=True):
- super(ClassifierHead_MLP, self).__init__()
- self.do_flatten = do_flatten
- self.additional_dense = nn.Linear(d_flatten, d_mlp)
- self.output_dense = nn.Linear(d_mlp, num_classes)
- self.dropout = nn.Dropout(dropout_rate)
- def forward(self, x, mask=None):
- if mask is not None:
- raise ValueError('mask is not supported for MLP head')
- if self.do_flatten:
- x = x.view(x.size(0), -1) # Flatten
- x = self.dropout(x)
- x = F.relu(self.additional_dense(x))
- x = self.dropout(x)
- x = self.output_dense(x)
- return x
- class ClassifierHead_AvgPool(nn.Module):
- def __init__(self, d_k, d_mlp, num_classes, dropout_rate, init_method=None):
- super(ClassifierHead_AvgPool, self).__init__()
- self.additional_dense = nn.Linear(d_k, d_mlp)
- self.output_dense = nn.Linear(d_mlp, num_classes)
- self.dropout = nn.Dropout(dropout_rate)
- if init_method is not None:
- apply_init_method([self.additional_dense, self.output_dense], init_method)
- def forward(self, x, mask=None):
- x = masked_mean(x, mask, dim=1)
- x = self.dropout(x)
- x = F.relu(self.additional_dense(x))
- x = self.dropout(x)
- x = self.output_dense(x)
- return x
- class ProjectionHead_AvgPool(nn.Module):
- def __init__(self, d_k, d_mlp, skip_mean=False):
- super(ProjectionHead_AvgPool, self).__init__()
- self.additional_dense = nn.Linear(d_k, d_mlp)
- self.output_dense = nn.Linear(d_mlp, d_mlp)
- self.skip_mean = skip_mean
- def forward(self, x, mask=None):
- if not self.skip_mean:
- x = masked_mean(x, mask=mask, dim=1)
- x = F.relu(self.additional_dense(x))
- x = self.output_dense(x)
- return x
- class TransformerLayer(nn.Module):
- def __init__(self, d_k, num_heads, d_mlp, dropout_rate):
- super(TransformerLayer, self).__init__()
- self.query_projection = nn.Linear(d_k, d_k)
- self.key_projection = nn.Linear(d_k, d_k)
- self.value_projection = nn.Linear(d_k, d_k)
- self.attention = nn.MultiheadAttention(d_k, num_heads, batch_first=True)
- self.norm1 = nn.LayerNorm(d_k)
- self.norm2 = nn.LayerNorm(d_k)
- self.ffn = nn.Sequential(
- nn.Linear(d_k, d_mlp),
- nn.ReLU(),
- nn.Linear(d_mlp, d_k)
- )
- self.dropout = nn.Dropout(dropout_rate)
- def forward(self, x, apply_dropout=False,attn_mask=None,key_padding_mask=None):
- # Projecting to query, key, and value
- query = self.query_projection(x)
- key = self.key_projection(x)
- value = self.value_projection(x)
- # Multi-Head Attention and Residual Connection
- att_out, _ = self.attention(query, key, value,attn_mask=attn_mask,key_padding_mask=key_padding_mask)
- x = self.norm1(x + att_out)
- # Feed-Forward Network and Residual Connection
- ffn_out = self.ffn(x)
- if apply_dropout:
- ffn_out = self.dropout(ffn_out)
- x = self.norm2(x + ffn_out)
- return x
- def masked_mean(x,mask=None,dim=1):
- #mask indicates which elements should be excluded from the mean
- if mask is None:
- x = torch.mean(x, dim=dim)
- else:
- #expand mask to the same dimentionality as x
- mask = mask.unsqueeze(-1)
- x = torch.sum(x * ~mask, dim=dim) / torch.sum(~mask, dim=dim)
- return x
- def apply_init_method(layers, init_method):
- if init_method == 'xavier':
- for layer in layers:
- nn.init.xavier_uniform_(layer.weight)
- nn.init.zeros_(layer.bias)
- elif init_method == 'kaiming':
- for layer in layers:
- nn.init.kaiming_uniform_(layer.weight)
- nn.init.zeros_(layer.bias)
- elif init_method == 'small_weights':
- for layer in layers:
- nn.init.uniform_(layer.weight, -0.01, 0.01)
- nn.init.zeros_(layer.bias)
- elif init_method == 'diag':
- for layer in layers:
- nn.init.eye_(layer.weight)
- nn.init.zeros_(layer.bias)
- else:
- raise ValueError('Unknown init method')
eb_models.py at commit c2b7506, under other · at the source
Overview
- Weizmann Institute of Science, Department of Brain Sciences, Rehovot, Israel
- Mohamed bin Zayed University of Artificial Intelligence, Abu Dhabi, United Arab Emirates
Abstract
Although the eye may appear static during fixation, it is in constant motion–transforming visual input into rich spatio-temporal streams of neuronal activity. These movements challenge the classical view that visual acuity derives from spatial sampling, suggesting that hyperacuity can emerge from precise temporal encoding. Here we show that artificial systems can exploit this principle using retina-like event-based (EB) sensing, a neuromorphic approach in which the sensor emits asynchronous spikes in response to luminance changes. Using an EB camera undergoing controlled “fixational” motion over tiny, pixelated images, we generated datasets in which recognition depends on sub-pixel information. We found that artificial neural networks trained on these spatio-temporal event streams relied crucially on the precise temporal information and outperformed conventional frame-based models. The learned representations also supported Vernier-style sub-pixel discrimination, demonstrating hyperacuity-like behavior in the artificial bio-mimetic system. These results show that active event-based sensing can use precise timing to recover spatial details that are unrecoverable from a static single frame. Together, these findings offer a new perspective on visual perception, open pathways for advancing neuromorphic engineering and energy-efficient AI vision systems, and provide a framework for testing hypotheses about biological vision.
Reproduced under the paper's license (CC BY), from the paper cited above.
Repositories
Its files are read in the Code ↔ Paper reader above, with 8 matches between paragraphs and lines of code.
zalandoresearch/fashion-mnist
b2617bb6d3ffa2e429640350f613e3291e10b141, 21 March 2022Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
14 files
- app.py, Python, 20 lines
- benchmark/
__init__.py , Python, 1 line - benchmark/
convnet.py , Python, 149 lines - benchmark/
runner.py , Python, 207 lines - configs.py, Python, 90 lines
- static/
js/ , JavaScript, 118 linesvue-binding.js - utils/
__init__.py , Python, 1 line - utils/
argparser.py , Python, 39 lines - utils/
helper.py , Python, 84 lines - utils/
mnist_reader.py , Python, 22 lines - visualization/
__init__.py , Python, 1 line - visualization/
project_zalando.py , Python, 43 lines - LICENSE, License, 7 lines
- README.md, Text, 283 lines
ahissar-lab/event-based-hyperacuity
c2b75060e1bb0f1334ca37da23b672483aae9e37, 9 July 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
32 files
- data_collection/
aedat_ds_preproc_paralle , Python, 497 linesl.py - data_collection/
events/ , Jupyter, 577 lines, 1 matchsyclop_acquire_dataset_2 0230623.ipynb - data_collection/
frames/ , Jupyter, 404 linessyclop_dvs_mnist_wiz_DAV IS_frames.ipynb - eb_contrastive.py, Python, 272 lines, 1 match
- eb_dataset.py, Python, 590 lines
- eb_models.py, Python, 588 lines, 3 matches
- eb_train.py, Python, 521 lines, 1 match
- losses.py, Python, 61 lines, 1 match
- lsf/
scripts/ , Shell, 25 linesrun_job_batch.sh - lsf/
scripts/ , Shell, 33 linessweep_stuff.sh - notebooks/
analyze_pkl_ds.ipynb , Jupyter, 277 lines - notebooks/
fig_acc_vs_jitter_allDS_ , Jupyter, 462 lines, 1 matchsupp.ipynb - notebooks/
rev1_fig_acc_over_framee , Jupyter, 594 linesxp_and_baseline.ipynb - notebooks/
rev2_fig4_vernier_raster , Jupyter, 200 lines_plot.ipynb - notebooks/
rev2_fig_acc_vs_jitter.i , Jupyter, 400 linespynb - notebooks/
rev2_figure1_system_and_ , Jupyter, 403 linesraw_data.ipynb - notebooks/
rev3_fig_accs_over_event , Jupyter, 634 liness_and_baselines.ipynb - notebooks/
revFinal1_FrameVernier.i , Jupyter, 440 linespynb - notebooks/
revFinal1_NMNIST_eventTr , Jupyter, 134 linesain.ipynb - notebooks/
revFinal1_augmentation_b , Jupyter, 320 linesy_tw.ipynb - notebooks/
revFinal1_contrastive.ip , Jupyter, 703 linesynb - notebooks/
revFinal1_fig_NMNISTacc_ , Jupyter, 237 linesvs_jitter.ipynb - notebooks/
revFinal1_material_for_c , Jupyter, 136 linesontrastive_illustration. ipynb - notebooks/
revFinal1_supp_accs_over , Jupyter, 442 lines_events_GRUavg_pool.ipyn b - notebooks/
revFinal1_supp_accs_over , Jupyter, 316 lines_events_NMNIST.ipynb - notebooks/
revFinal1_supp_accs_over , Jupyter, 427 lines_time.ipynb - notebooks/
revFinal1_vernier.ipynb , Jupyter, 696 lines - notebooks/
tests.ipynb , Jupyter, 28 lines - parser.py, Python, 250 lines
- utils.py, Python, 263 lines
- LICENSE.md, License, 109 lines
- README.md, Text, 79 lines
Zenodo 20777652
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
- 27 September 2026: the link answers (HTTP 200)
32 files
- data_collection/
aedat_ds_preproc_paralle , Python, 497 linesl.py - data_collection/
events/ , Jupyter, 577 linessyclop_acquire_dataset_2 0230623.ipynb - data_collection/
frames/ , Jupyter, 404 linessyclop_dvs_mnist_wiz_DAV IS_frames.ipynb - eb_contrastive.py, Python, 272 lines
- eb_dataset.py, Python, 590 lines
- eb_models.py, Python, 588 lines
- eb_train.py, Python, 521 lines
- losses.py, Python, 61 lines
- lsf/
scripts/ , Shell, 25 linesrun_job_batch.sh - lsf/
scripts/ , Shell, 33 linessweep_stuff.sh - notebooks/
analyze_pkl_ds.ipynb , Jupyter, 277 lines - notebooks/
fig_acc_vs_jitter_allDS_ , Jupyter, 462 linessupp.ipynb - notebooks/
rev1_fig_acc_over_framee , Jupyter, 594 linesxp_and_baseline.ipynb - notebooks/
rev2_fig4_vernier_raster , Jupyter, 200 lines_plot.ipynb - notebooks/
rev2_fig_acc_vs_jitter.i , Jupyter, 400 linespynb - notebooks/
rev2_figure1_system_and_ , Jupyter, 403 linesraw_data.ipynb - notebooks/
rev3_fig_accs_over_event , Jupyter, 634 liness_and_baselines.ipynb - notebooks/
revFinal1_FrameVernier.i , Jupyter, 440 linespynb - notebooks/
revFinal1_NMNIST_eventTr , Jupyter, 134 linesain.ipynb - notebooks/
revFinal1_augmentation_b , Jupyter, 320 linesy_tw.ipynb - notebooks/
revFinal1_contrastive.ip , Jupyter, 703 linesynb - notebooks/
revFinal1_fig_NMNISTacc_ , Jupyter, 237 linesvs_jitter.ipynb - notebooks/
revFinal1_material_for_c , Jupyter, 136 linesontrastive_illustration. ipynb - notebooks/
revFinal1_supp_accs_over , Jupyter, 442 lines_events_GRUavg_pool.ipyn b - notebooks/
revFinal1_supp_accs_over , Jupyter, 316 lines_events_NMNIST.ipynb - notebooks/
revFinal1_supp_accs_over , Jupyter, 427 lines_time.ipynb - notebooks/
revFinal1_vernier.ipynb , Jupyter, 696 lines - notebooks/
tests.ipynb , Jupyter, 28 lines - parser.py, Python, 250 lines
- utils.py, Python, 263 lines
- LICENSE.md, License, 109 lines
- README.md, Text, 79 lines
Code availability
The code generated in this study is publicly available at Github (https://
Reproduced under the paper's license (CC BY), from the paper cited above.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 3 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 72 scripts, each with its path and the digest of its content;
- 8 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
Datasets cited
- github.com/
rois-codh/ , at github.com; found in “Data availability”kmnist - kaggle.com/
datasets/ , at Kaggle; found in “Data availability”hojjatk - kaggle.com/
datasets/ , at Kaggle; found in “Data availability”khoahongg - zenodo:20973756, at Zenodo; found in “Data availability”
Data Availability Statement
The datasets generated and used in this study (including tiny event-based and tiny frame-based versions) have been deposited in Zenodo and are publicly available at https://
The code generated in this study is publicly available at Github (https://
Reproduced under the paper's license (CC BY), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 6 authors, 3 keywords, 7 MeSH terms, 1 funder, 49 references.
Cite
This paper
Assa, E., Rivkind, A., Kreiserman, M., Khan, F. S., Khan, S., & Ahissar, E. (2026). Temporal coding enables hyperacuity in event-based vision. Nature communications, 17(1), 9951. https://
BibTeX
@article{assa2026tempora
author = {Assa, Eldad and Rivkind, Alexander and Kreiserman, Michael and Khan, Fahad Shahbaz and Khan, Salman and Ahissar, Ehud},
title = {{Temporal coding enables hyperacuity in event-based vision}},
journal = {Nature communications},
year = {2026},
month = aug,
volume = {17},
number = {1},
pages = {9951},
publisher = {Nature Publishing Group},
issn = {2041-1723},
doi = {10.1038/
url = {https://
pmid = {42754584},
pmcid = {PMC13586331}
}
RIS
TY - JOUR
AU - Assa, Eldad
AU - Rivkind, Alexander
AU - Kreiserman, Michael
AU - Khan, Fahad Shahbaz
AU - Khan, Salman
AU - Ahissar, Ehud
TI - Temporal coding enables hyperacuity in event-based vision
T2 - Nature communications
J2 - Nat Commun
PY - 2026
DA - 2026/
VL - 17
IS - 1
SP - 9951
SN - 2041-1723
PB - Nature Publishing Group
DO - 10.1038/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1038/
"type": "article-journal",
"title": "Temporal coding enables hyperacuity in event-based vision",
"container-title": "Nature communications",
"author": [
{
"family": "Assa",
"given": "Eldad"
},
{
"family": "Rivkind",
"given": "Alexander"
},
{
"family": "Kreiserman",
"given": "Michael"
},
{
"family": "Khan",
"given": "Fahad Shahbaz"
},
{
"family": "Khan",
"given": "Salman"
},
{
"family": "Ahissar",
"given": "Ehud"
}
],
"container-title-short":
"volume": "17",
"issue": "1",
"page": "9951",
"DOI": "10.1038/
"PMID": "42754584",
"PMCID": "PMC13586331",
"ISSN": "2041-1723",
"publisher": "Nature Publishing Group",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
20
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1038/s41467-026-72057-9 [code]
- Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.Journal: Nature communicationsIn common: TensorFlow, OpenCV, PyTorch, 5 other tools, 1 reference
- [2] doi:10.1038/s41467-026-74358-5 [code]
- Brain-inspired spatial intelligence for embodied agents.Journal: Nature communicationsIn common: TensorFlow, OpenCV, PyTorch, 5 other tools, cognitive
- [3] doi:10.1038/s41598-026-43529-1 [code]
- A spiking neural network inspired by neuroscience and psychology for Western mode- and key-conditioned music learning and composition.Journal: Scientific reportsIn common: TensorFlow, OpenCV, PyTorch, 5 other tools, cognitive
- [4] doi:10.1162/imag.a.1207 [code]
- Investigating the temporal dynamics and modeling of mid-level feature representations in humans.Journal: Imaging neuroscience (Cambridge, Mass.)In common: OpenCV, PyTorch, scikit-learn, 4 other tools, cognitive, 1 reference
- [5] doi:10.1038/s42003-026-10957-8 [code]
- Brain defence by the extracellular matrix protein Cochlin.Journal: Communications biologyIn common: TensorFlow, OpenCV, PyTorch, 5 other tools
- [6] doi:10.1371/journal.pcbi.1014571 [code]
- SynAPSeg: A novel dataset and image analysis framework for deep learning-based synapse detection and quantification.Journal: PLoS computational biologyIn common: TensorFlow, OpenCV, PyTorch, 5 other tools
- [7] doi:10.1093/jnen/nlaf152 [code]
- Clinical and pathologic correlations of machine learning quantification of Aβ deposits across 3 brain regions of decedents with Alzheimer disease.Journal: Journal of neuropathology and experimental neurologyIn common: TensorFlow, OpenCV, PyTorch, 5 other tools
- [8] doi:10.1016/j.patter.2026.101538 [code]
- A multi-modal foundation model for brain disease diagnosis and medical imaging.Journal: Patterns (New York, N.Y.)In common: TensorFlow, OpenCV, PyTorch, 5 other tools
- [9] doi:10.1038/s41597-025-05174-7 [code]
- A large-scale MEG and EEG dataset for object recognition in naturalistic scenesJournal: n/aIn common: TensorFlow, OpenCV, PyTorch, 5 other tools
- [10] doi:10.1126/sciadv.aed3650 [code]
- Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive &
lt;i& gt;m/ z& lt;/ i& gt; mapping and exploration. Journal: Science advancesIn common: TensorFlow, OpenCV, PyTorch, 5 other tools
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 3 repositories of the authors' code, each at its verified commit and with its license, 72 scripts, and 8 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:103d397cde13acc1…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
