fovi.models.omni_isotropic

Fixed-count isotropic patch embeddings with per-image CMF selection.

class fovi.models.omni_isotropic.Sequence

Bases: Reversible, Collection

All the operations on a read-only sequence.

Concrete subclasses must override __new__ or __init__, __getitem__, and __len__.

count(value) → integer -- return number of occurrences of value
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

class fovi.models.omni_isotropic.DictConfig(content: Dict[str | bytes | int | Enum | float | bool, Any] | DictConfig | Any, key: Any = None, parent: Box | None = None, ref_type: Any | Type[Any] = Any, key_type: Any | Type[Any] = Any, element_type: Any | Type[Any] = Any, is_optional: bool = True, flags: Dict[str, bool] | None = None)[source]

Bases: BaseContainer, MutableMapping[Any, Any]

__init__(content: Dict[str | bytes | int | Enum | float | bool, Any] | DictConfig | Any, key: Any = None, parent: Box | None = None, ref_type: Any | Type[Any] = Any, key_type: Any | Type[Any] = Any, element_type: Any | Type[Any] = Any, is_optional: bool = True, flags: Dict[str, bool] | None = None) → None[source]
copy() → DictConfig[source]
get(key: str | bytes | int | Enum | float | bool, default_value: Any = None) → Any[source]

Return the value for key if key is in the dictionary, else default_value (defaulting to None).

pop(k[, d]) → v, remove specified key and return the corresponding value.[source]

If key is not found, d is returned if given, otherwise KeyError is raised.

keys() → a set-like object providing a view on D's keys[source]
items() → a set-like object providing a view on D's items[source]
setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D[source]
items_ex(resolve: bool = True, keys: Sequence[str | bytes | int | Enum | float | bool] | None = None) → List[Tuple[str | bytes | int | Enum | float | bool, Any]][source]
_promote(type_or_prototype: Type[Any] | None) → None[source]

Retypes a node. This should only be used in rare circumstances, where you want to dynamically change the runtime structured-type of a DictConfig. It will change the type and add the additional fields based on the input class or object

_to_object() → Any[source]

Instantiate an instance of self._metadata.object_type. This requires self to be a structured config. Nested subconfigs are converted by calling OmegaConf.to_object.

fovi.models.omni_isotropic.get_in_out_coords(in_res, fov, cmf_a, stride, style='isotropic', auto_match_cart_resources=1, in_cart_res=None, device='cuda', in_coords=None, force_out_match_less_than=True, max_out_coord_val=1, isotropic_plotting_type='v1like', fov_type='circular', field_geometry='planar', radius_norm=2.0)[source]

Convenience function to generate input and output coordinates for KNN layers.

Parameters:
  • in_res (int) – Input resolution.

  • fov (float) – Field of view diameter in degrees.

  • cmf_a (float) – a parameter in CMF: M(r) = 1/(r+a). Smaller = stronger foveation.

  • stride (int) – Stride factor for downsampling.

  • style (str, optional) – Sampling style. Defaults to ‘isotropic’.

  • auto_match_cart_resources (int, optional) – Auto-match parameter. Defaults to 1.

  • in_cart_res (int, optional) – Input cartesian resolution. Defaults to None.

  • device (str, optional) – PyTorch device. Defaults to ‘cuda’.

  • in_coords (SamplingCoords, optional) – Pre-computed input coordinates. Defaults to None.

  • force_out_match_less_than (bool, optional) – If auto_match_cart_resources, this determines whether the output number is constrained to not be greater than the target cartesian resolution (if false, chooses the closest match, which could be greater). Defaults to True.

  • max_out_coord_val (int or str, optional) – Maximum output coordinate value. Defaults to 1.

Returns:

A tuple containing:
  • SamplingCoords: Input coordinates

  • SamplingCoords: Output coordinates

  • int: Output cartesian resolution

Return type:

tuple

class fovi.models.omni_isotropic.IncidenceBank(tables: list[tuple[ndarray, ndarray, ndarray, ndarray]], samples: int, patches: int, reference_bins: int)[source]

Bases: Module

Geometry-only tables; reconstructed from config, never checkpoint weights.

__init__(tables: list[tuple[ndarray, ndarray, ndarray, ndarray]], samples: int, patches: int, reference_bins: int) → None[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

validate(x: Tensor, levels: Tensor) → None[source]

Check dimensions and level range before passing raw pointers to CUDA.

launch(x: Tensor, levels: Tensor, out: Tensor, backward: bool = False) → None[source]

Execute deterministic bin reductions without sorting or splitting the batch.

reference(x: Tensor, levels: Tensor) → Tensor[source]

Slow differentiable CPU oracle for inspection and correctness tests.

forward(x: Tensor, levels: Tensor) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

fovi.models.omni_isotropic.incidence_tables(indices: ndarray, bins: ndarray, samples: int, reference_bins: int) → tuple[ndarray, ndarray, ndarray, ndarray][source]

Build forward and transpose CSR tables, excluding the zero-padding token.

class fovi.models.omni_isotropic.SamplingCoords(fov, cmf_a, res, device='cpu', style='isotropic', dtype=torch.float, max_val=1, isotropic_plotting_type='v1like', fov_type='circular', field_geometry='planar', radius_norm=2.0)[source]

Bases: object

Object for storing multiple coordinate systems relevant to a set of visual field samples.

Parameters:
  • fov (float) – Field-of-view in degrees.

  • cmf_a (float) – A parameter from the CMF: M(r)=1/(r+a). Smaller a = stronger foveation.

  • res (int) – Resolution, corresponding to the side length of a cartesian grid or the number of radii in polar (before any adjustments are made to match a target cartesian grid).

  • device (str) – What device to operate on.

  • style (str) – What type of sampling.

  • dtype (torch.dtype) – What data type to use.

  • fov_type (str) – One of 'circular', 'square', or 'wang'. The last is only valid for warped Cartesian sensor styles.

  • radius_norm (float) – Norm measuring native-plane radius for warped Cartesian styles. 2.0 gives circular iso-eccentricity shells; inf gives square shells, which pair with fov_type='square' to retain every cell.

__init__(fov, cmf_a, res, device='cpu', style='isotropic', dtype=torch.float, max_val=1, isotropic_plotting_type='v1like', fov_type='circular', field_geometry='planar', radius_norm=2.0)[source]
as_grid(values: Tensor, sample_dim: int = -1) → Tensor[source]

Replace a canonical sample axis with the sensor’s image axes.

Cartesian grids return upright rows down and columns right. Log-polar grids retain their radius/angle ordering. Other axes are unchanged.

Parameters:
  • values – Tensor with one axis containing all canonical samples.

  • sample_dim – Sample axis; use zero for coordinates shaped (N, 2).

Returns:

Tensor with the sample axis replaced by height and width.

native_to_visual(coordinates: Tensor) → Tensor[source]

Map (…, 2) native Cartesian warp coordinates to the visual chart.

Visual chart radius one is half the configured FoV. For spherical geometry this is angular eccentricity, not a pinhole projection. The unbounded chart includes masked cells outside the model footprint; renderers must handle their own angular padding domain.

visual_to_native(coordinates: Tensor) → Tensor[source]

Map (…, 2) normalized visual-chart positions to the native grid.

pad_cartesian(padding_distance=0.5, device=None, dtype=None)[source]

Generate additional cartesian coordinates for padding around the sampling grid.

Parameters:
  • padding_distance (float) – Padding extent in normalized coordinates. For spherical radial grids, measured from the real retinal rim, retaining at least one complete neighboring ring. Planar/legacy radial grids retain the historical interval starting at the first outer ring, which can overshoot the requested rim margin by one ring. Preserve that behavior for checkpoint KNN compatibility. Warped Cartesian and log-polar layouts pad in their own grid coordinates using a whole number of grid intervals.

  • device (str, optional) – Device to place the coordinates on. Defaults to None.

  • dtype (torch.dtype, optional) – Data type for the coordinates. Defaults to None.

Returns:

Additional cartesian coordinates for padding.

Return type:

torch.Tensor

get_strided_coords(stride, auto_match_cart_resources=0, in_cart_res=None, force_less_than=True, max_val=1)[source]

Return a strided version of the coordinates.

Parameters:
  • stride (int) – Stride factor for downsampling coordinates.

  • auto_match_cart_resources (int) – Automatic matching parameter for cartesian resources.

  • in_cart_res (int, optional) – Input cartesian resolution. Required for ‘fixn’ style.

  • force_less_than (bool, optional) – Whether to force less than target resolution. Defaults to True.

  • max_val (float, optional) – Maximum value for coordinates. Defaults to 1.

Returns:

A tuple containing:
  • SamplingCoords: New SamplingCoords object with strided coordinates.

  • int: Number of output radii.

  • int: Corresponding output cartesian resolution.

Return type:

tuple

to(device=None, dtype=None)[source]

Move the SamplingCoords object to a different device and/or change data type.

Parameters:
  • device (str, optional) – Target device. Defaults to None.

  • dtype (torch.dtype, optional) – Target data type. Defaults to None.

Returns:

SamplingCoords object on the specified device/dtype.

Return type:

SamplingCoords

get_scatter_sizes()[source]

Calculate approximate size to be used for plotting in scatter plots.

Scales linearly with eccentricity, as occurs in KNN-sampling of the sensor manifold. However, this is not precisely tuned to the particular warping parameters.

Returns:

Receptive field sizes for each sampling point.

Return type:

torch.Tensor

clone(fov=None, cmf_a=None, resolution=None, device=None, style=None, dtype=None, max_val=None, isotropic_plotting_type=None, fov_type=None, field_geometry=None, radius_norm=None)[source]

Return a deep copy of the SamplingCoords object with optional parameter overrides.

Parameters:
  • fov (float, optional) – Field-of-view in degrees. Defaults to current value.

  • cmf_a (float, optional) – A parameter from the CMF. Defaults to current value.

  • resolution (int, optional) – Resolution parameter. Defaults to current value.

  • device (str, optional) – Device to place coordinates on. Defaults to current value.

  • style (str, optional) – Sampling style. Defaults to current value.

  • dtype (torch.dtype, optional) – Data type. Defaults to current value.

  • max_val (float, optional) – Maximum coordinate value. Defaults to current value.

Returns:

A new SamplingCoords object with the specified parameters.

Return type:

SamplingCoords

fovi.models.omni_isotropic.is_cmf_sequence(cmf_a: float | Sequence[float]) → bool[source]

Recognize Python and OmegaConf lists without treating sentinels as lists.

fovi.models.omni_isotropic.validate_cmf_values(cmf_a: Sequence[float]) → tuple[float, ...][source]

Validate an explicit bank of finite, positive CMF parameters in degrees.

fovi.models.omni_isotropic.geodesic_cache_directory() → Path | None[source]

Resolve the model’s persistent cache; an empty override disables caching.

fovi.models.omni_isotropic.patch_geodesic_distances(inputs: SamplingCoords, patches: SamplingCoords, cache_dir: Path | None = None) → Tensor[source]

Return [real + padding samples, patches] distances on the cortical mesh.

Triangulate in the visual coordinate chart, but measure on the embedded cortical surface. Include the actual patch centers as mesh vertices, rather than moving each source to its nearest retinal sample. Distances are exact on this piecewise-linear mesh, an approximation to the smooth manifold. Construction is CPU-only and stays outside the training hot path.

fovi.models.omni_isotropic.vis_cartesian_to_cortical_cartesian_coords(cartesian_coords, cmf_a, fov, as_tensor=False, device='cpu', k=10, field_geometry='planar')[source]
  • Map visual cartesian coordinates to 3d cortical cartesian coordinates using the 3D cortical model.

  • We use this when coordinates are sampled elsewhere, and we want to map them into the 3d model for receptive field sampling.

  • This is the main function we use to implement the cortical sensor manifold, in combination with isotropically magnified visual field sampling

Note, the CMF is \(M(r)=\frac{k}{r+a}\)

Parameters:
  • cartesian_coords (np.ndarray) – (n,2) visual cartesian coordinates in (x,y) format

  • cmf_a (float) – \(a\) value in the CMF, in degrees

  • fov (float) – field-of-view in degrees

  • as_tensor (bool, optional) – whether to return as a tensor. Defaults to False.

  • device (str or torch.Device, optional) – if as_tensor=True, which device to use

  • k (float, optional) – scaling value for CMF

Returns:

(n, 3) array of cortical cartesian points \((x_c, y_c, z)\)

Return type:

np.ndarray or torch.Tensor

class fovi.models.omni_isotropic.KNNPartitioningPatchEmbedding(in_channels: int, embed_dim: int, in_res: int, fov: float, cmf_a: float, style: str = 'isotropic', auto_match_cart_resources: bool = True, in_cart_res: int = 224, cart_patch_size=16, device='cuda', force_patches_less_than_matched=True, transposed=False, max_coord_val='auto', sample_cortex='geodesic', isotropic_plotting_type='v1like', fov_type='circular', radius_norm=2.0, in_coords=None, out_coords=None, field_geometry='planar', precomputed_distances: Tensor | None = None, **kwargs)[source]

Bases: KNNPatchEmbedding

static _stable_neighbor_order(distances)[source]

Order neighbors by distance, breaking ties by candidate index.

__init__(in_channels: int, embed_dim: int, in_res: int, fov: float, cmf_a: float, style: str = 'isotropic', auto_match_cart_resources: bool = True, in_cart_res: int = 224, cart_patch_size=16, device='cuda', force_patches_less_than_matched=True, transposed=False, max_coord_val='auto', sample_cortex='geodesic', isotropic_plotting_type='v1like', fov_type='circular', radius_norm=2.0, in_coords=None, out_coords=None, field_geometry='planar', precomputed_distances: Tensor | None = None, **kwargs)[source]

Initialize KNN partitioning patch embedding layer.

Parameters:
  • in_channels – Number of input channels

  • embed_dim – Embedding dimension for tokens

  • in_res – Input resolution

  • fov – Field of view parameter for foveated sampling

  • cmf_a – a parameter controlling foveated sampling via the CMF

  • style – Sampling style (‘isotropic’, etc.)

  • auto_match_cart_resources – Whether to automatically match cartesian resources

  • in_cart_res – Resolution of input cartesian grid

  • cart_patch_size – Size of cartesian patches

  • device – Device to run on

  • force_patches_less_than_matched – Whether to force patches to be less than matched

  • transposed – Whether to transpose output

  • max_coord_val – Maximum coordinate value

  • sample_cortex – Cortex sampling method

  • fov_type – Shape of the sampled field of view

  • in_coords – Optional precomputed input coordinates

  • out_coords – Optional precomputed output coordinates

  • **kwargs – Additional arguments passed to parent class

fovi.models.omni_isotropic.is_omni_isotropic(cfg: DictConfig) → bool[source]

Whether the configured backbone needs a per-image isotropic geometry index.

fovi.models.omni_isotropic.patch_positions(patches: SamplingCoords, space: str) → Tensor[source]

Build fixed patch positions in row/column order, plus height for 3D.

Both cortical representations share unit cortical radial length at the field boundary. The 3D surface uses a single scalar for every axis.

class fovi.models.omni_isotropic.OmniIsotropicPatchEmbedding(*, fov: float, cmf_a: Sequence[float], resolution: int, patch_size: int, reference_side: int, in_channels: int, embed_dim: int, sample_cortex: bool | str, device: str | device, position_coordinate_space: str = 'cartesian', patch_max_coord_val: float | str = 1.0, field_geometry: str = 'planar')[source]

Bases: Module

Share one learned kernel across independently calibrated geometry levels.

__init__(*, fov: float, cmf_a: Sequence[float], resolution: int, patch_size: int, reference_side: int, in_channels: int, embed_dim: int, sample_cortex: bool | str, device: str | device, position_coordinate_space: str = 'cartesian', patch_max_coord_val: float | str = 1.0, field_geometry: str = 'planar') → None[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

load_conv2d_weights(conv: Conv2d) → None[source]

Orient and bilinearly resample the pretrained reference weight field.

Matches the scalar KNN loader. Preserve pointwise amplitude: each real sample still contributes once per neighborhood, regardless of bin count. Area or L2 normalization would artificially attenuate the larger kernel.

forward(x: Tensor, cmf_indices: Tensor) → Tensor[source]

Return [batch, channels, patches], retaining the native DINO contract.