fovi.arch.knn_bank

Per-image sparse geometry selection followed by a shared patch projection.

fovi.arch.knn_bank.cache(user_function, /)[source]

Simple lightweight unbounded cache. Sometimes called “memoize”.

class fovi.arch.knn_bank.Path(*args, **kwargs)[source]

Bases: PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

classmethod cwd()[source]

Return a new path pointing to the current working directory (as returned by os.getcwd()).

classmethod home()[source]

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

samefile(other_path)[source]

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

iterdir()[source]

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

glob(pattern)[source]

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

rglob(pattern)[source]

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

absolute()[source]

Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.

Use resolve() to get the canonical path to a file.

resolve(strict=False)[source]

Make the path absolute, resolving all symlinks on the way and also normalizing it.

stat(*, follow_symlinks=True)[source]

Return the result of the stat() system call on this path, like os.stat() does.

owner()[source]

Return the login name of the file owner.

group()[source]

Return the group name of the file gid.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[source]

Open the file pointed by this path and return a file object, as the built-in open() function does.

read_bytes()[source]

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)[source]

Open the file in text mode, read it, and close the file.

write_bytes(data)[source]

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)[source]

Open the file in text mode, write to it, and close the file.

Return the path to which the symbolic link points.

touch(mode=0o666, exist_ok=True)[source]

Create this file with the given access mode, if it doesn’t exist.

mkdir(mode=0o777, parents=False, exist_ok=False)[source]

Create a new directory at this given path.

chmod(mode, *, follow_symlinks=True)[source]

Change the permissions of the path, like os.chmod().

lchmod(mode)[source]

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Remove this file or link. If the path is a directory, use rmdir() instead.

rmdir()[source]

Remove this directory. The directory must be empty.

lstat()[source]

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

rename(target)[source]

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)[source]

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

exists()[source]

Whether this path exists.

is_dir()[source]

Whether this path is a directory.

is_file()[source]

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()[source]

Check if this path is a POSIX mount point

Whether this path is a symbolic link.

is_block_device()[source]

Whether this path is a block device.

is_char_device()[source]

Whether this path is a character device.

is_fifo()[source]

Whether this path is a FIFO.

is_socket()[source]

Whether this path is a socket.

expanduser()[source]

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

class fovi.arch.knn_bank.FunctionCtx[source]

Bases: object

output_grad_dtypes: tuple[dtype | None, ...] | None
property input_grad_buffers: tuple[Tensor | None, ...]

Return existing buffers for accumulating gradients of this Function’s inputs.

Each entry corresponds to an argument passed to forward(), in the same order. Each entry is None or the autograd engine’s current InputBuffer for that input. A non-None buffer contains gradient contributions already produced during the current backward. A custom backward may accumulate its contribution directly into the buffer and return None for that input, fusing gradient computation with accumulation and avoiding a separate gradient tensor.

Availability follows backward execution order and is independent for each input. An entry is None when no earlier producer has contributed to that input, or when the existing buffer is aliased or cannot safely be updated in place.

For example, x has another forward use while weight does not. The custom backward conditionally fuses accumulation only for grad_x:

>>> # xdoctest: +SKIP
>>> class Matmul(torch.autograd.Function):
>>>     @staticmethod
>>>     def forward(ctx, x, weight):
>>>         ctx.save_for_backward(x, weight)
>>>         return x @ weight
>>>
>>>     @staticmethod
>>>     def backward(ctx, grad_output):
>>>         x, weight = ctx.saved_tensors
>>>         x_buffer, _ = ctx.input_grad_buffers
>>>         if x_buffer is not None:
>>>             # Computes grad_x and adds it to the existing buffer.
>>>             matmul_backward_input_acc(
>>>                 grad_output, weight, acc_into=x_buffer
>>>             )
>>>             grad_x = None
>>>         else:
>>>             grad_x = matmul_backward_input(grad_output, weight)
>>>         grad_weight = matmul_backward_weight(grad_output, x)
>>>         return grad_x, grad_weight
>>>
>>> loss = Matmul.apply(x, weight).sum() + other_op(x).sum()

If other_op produces its contribution first, x_buffer can expose that partial sum. If Matmul runs first, x_buffer is None and it returns a separate tensor instead. The fallback lets the function work under either ordering.

Warning

A returned buffer is valid only while the current custom backward invocation is running. Mutate it synchronously and do not retain it. A later producer may replace the engine’s buffer, making a retained tensor stale.

After receiving a non-None buffer, calling backward or grad before the custom backward returns raises an error.

All engine-scheduled producers that use or subsequently update an exposed buffer must execute on the same device, autograd engine thread, and stream.

This property is available only while a Python custom backward is executing during an eager, first-order backward(), torch.autograd.backward(), or torch.autograd.grad() call. It is unavailable with create_graph=True, anomaly detection, a post-hook on the producing autograd node, or stale capture stream overrides.

Note

For a leaf input, a non-None entry exposes its execution-local InputBuffer, not its existing .grad. All contributions are first combined in that buffer. During backward, AccumulateGrad then runs once with the completed buffer to update .grad and run its usual hooks. torch.autograd.grad() instead returns the completed buffer without updating .grad.

During backward, a custom backward that instead accumulates directly into a leaf .grad and returns None does not use this interface. It is responsible for managing .grad state, including initialization and lifetime, synchronization with all other producers, and any AccumulateGrad hook behavior bypassed by the direct write.

save_for_backward(*tensors: Tensor)[source]

Save given tensors for a future call to backward().

save_for_backward should be called at most once, in either the setup_context() or forward() methods, and only with tensors.

All tensors intended to be used in the backward pass should be saved with save_for_backward (as opposed to directly on ctx) to prevent incorrect gradients and memory leaks, and enable the application of saved tensor hooks. See torch.autograd.graph.saved_tensors_hooks. See Extending torch.autograd for more details.

Note that if intermediary tensors, tensors that are neither inputs nor outputs of forward(), are saved for backward, your custom Function may not support double backward. Custom Functions that do not support double backward should decorate their backward() method with @once_differentiable so that performing double backward raises an error. If you’d like to support double backward, you can either recompute intermediaries based on the inputs during backward or return the intermediaries as the outputs of the custom Function. See the double backward tutorial for more details.

In backward(), saved tensors can be accessed through the saved_tensors attribute. Before returning them to the user, a check is made to ensure they weren’t used in any in-place operation that modified their content.

Arguments can also be None. This is a no-op.

See Extending torch.autograd for more details on how to use this method.

Example:

>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
>>> class Func(Function):
>>>     @staticmethod
>>>     def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int):
>>>         w = x * z
>>>         out = x * y + y * z + w * y
>>>         ctx.save_for_backward(x, y, w, out)
>>>         ctx.z = z  # z is not a tensor
>>>         return out
>>>
>>>     @staticmethod
>>>     @once_differentiable
>>>     def backward(ctx, grad_out):
>>>         x, y, w, out = ctx.saved_tensors
>>>         z = ctx.z
>>>         gx = grad_out * (y + y * z)
>>>         gy = grad_out * (x + z + w)
>>>         gz = None
>>>         return gx, gy, gz
>>>
>>> a = torch.tensor(1., requires_grad=True, dtype=torch.double)
>>> b = torch.tensor(2., requires_grad=True, dtype=torch.double)
>>> c = 4
>>> d = Func.apply(a, b, c)
save_for_forward(*tensors: Tensor)[source]

Save given tensors for a future call to jvp().

save_for_forward should be called at most once, in either the setup_context() or forward() methods, and all arguments should be tensors.

In jvp(), saved objects can be accessed through the saved_tensors attribute.

Arguments can also be None. This is a no-op.

See Extending torch.autograd for more details on how to use this method.

Example:

>>> # xdoctest: +SKIP
>>> class Func(torch.autograd.Function):
>>>     @staticmethod
>>>     def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int):
>>>         ctx.save_for_backward(x, y)
>>>         ctx.save_for_forward(x, y)
>>>         ctx.z = z
>>>         return x * y * z
>>>
>>>     @staticmethod
>>>     def jvp(ctx, x_t, y_t, _):
>>>         x, y = ctx.saved_tensors
>>>         z = ctx.z
>>>         return z * (y * x_t + x * y_t)
>>>
>>>     @staticmethod
>>>     def vjp(ctx, grad_out):
>>>         x, y = ctx.saved_tensors
>>>         z = ctx.z
>>>         return z * grad_out * y, z * grad_out * x, None
>>>
>>>     a = torch.tensor(1., requires_grad=True, dtype=torch.double)
>>>     t = torch.tensor(1., dtype=torch.double)
>>>     b = torch.tensor(2., requires_grad=True, dtype=torch.double)
>>>     c = 4
>>>
>>>     with fwAD.dual_level():
>>>         a_dual = fwAD.make_dual(a, t)
>>>         d = Func.apply(a_dual, b, c)
mark_dirty(*args: Tensor)[source]

Mark given tensors as modified in an in-place operation.

This should be called at most once, in either the setup_context() or forward() methods, and all arguments should be inputs.

Every tensor that’s been modified in-place in a call to forward() should be given to this function, to ensure correctness of our checks. It doesn’t matter whether the function is called before or after modification.

Examples::
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
>>> class Inplace(Function):
>>>     @staticmethod
>>>     def forward(ctx, x):
>>>         x_npy = x.numpy() # x_npy shares storage with x
>>>         x_npy += 1
>>>         ctx.mark_dirty(x)
>>>         return x
>>>
>>>     @staticmethod
>>>     @once_differentiable
>>>     def backward(ctx, grad_output):
>>>         return grad_output
>>>
>>> a = torch.tensor(1., requires_grad=True, dtype=torch.double).clone()
>>> b = a * a
>>> Inplace.apply(a)  # This would lead to wrong gradients!
>>>                   # but the engine would not know unless we mark_dirty
>>> # xdoctest: +SKIP
>>> b.backward() # RuntimeError: one of the variables needed for gradient
>>>              # computation has been modified by an inplace operation
mark_shared_storage(*pairs)[source]
mark_non_differentiable(*args: Tensor)[source]

Mark outputs as non-differentiable.

This should be called at most once, in either the setup_context() or forward() methods, and all arguments should be tensor outputs.

This will mark outputs as not requiring gradients, increasing the efficiency of backward computation. You still need to accept a gradient for each output in backward(), but it’s always going to be a zero tensor with the same shape as the shape of a corresponding output.

This is used e.g. for indices returned from a sort. See example::
>>> class Func(Function):
>>>     @staticmethod
>>>     def forward(ctx, x):
>>>         sorted, idx = x.sort()
>>>         ctx.mark_non_differentiable(idx)
>>>         ctx.save_for_backward(x, idx)
>>>         return sorted, idx
>>>
>>>     @staticmethod
>>>     @once_differentiable
>>>     def backward(ctx, g1, g2):  # still need to accept g2
>>>         x, idx = ctx.saved_tensors
>>>         grad_input = torch.zeros_like(x)
>>>         grad_input.index_add_(0, idx, g1)
>>>         return grad_input
set_output_grad_dtype(*dtypes: dtype | None) → None[source]

Declare the gradient dtype for each of this Function’s outputs.

This should be called at most once, from either the setup_context() or forward() methods. The number of declarations must match the number of returned values, and each argument corresponds positionally to the output at the same index.

For each output, pass the dtype your backward should receive its gradient in:

  • Pass a torch.dtype and the engine guarantees the gradient handed to backward has that dtype. This is only valid for a differentiable Tensor output.

  • Pass None and the gradient is handed to backward with whatever dtype it already has. This is also the only valid choice for a non-Tensor or non-differentiable output, which has no gradient.

  • Omit this call (or pass the output’s own dtype) and the gradient is handed to backward in the output’s dtype, which is the default.

For example:

>>> # xdoctest: +SKIP
>>> @staticmethod
>>> def forward(ctx, x):
>>>     t1 = x.sin()
>>>     t2 = x.cos()
>>>     t3 = x.tan()
>>>     ctx.set_output_grad_dtype(torch.float32, t2.dtype, None, None)
>>>     return t1, t2, t3, "not a tensor"

This ensures that backward receives t1’s gradient in float32, keeps the default behavior for t2’s gradient via t2.dtype, passes t3’s gradient through uncast with None, and uses None as the placeholder for the trailing non-Tensor output.

set_materialize_grads(value: bool)[source]

Set whether to materialize grad tensors. Default is True.

This should be called only from either the setup_context() or forward() methods.

If True, undefined grad tensors will be expanded to tensors full of zeros prior to calling the backward() and jvp() methods.

Example:

>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
>>> class SimpleFunc(Function):
>>>     @staticmethod
>>>     def forward(ctx, x):
>>>         return x.clone(), x.clone()
>>>
>>>     @staticmethod
>>>     @once_differentiable
>>>     def backward(ctx, g1, g2):
>>>         return g1 + g2  # No check for None necessary
>>>
>>> # We modify SimpleFunc to handle non-materialized grad outputs
>>> class Func(Function):
>>>     @staticmethod
>>>     def forward(ctx, x):
>>>         ctx.set_materialize_grads(False)
>>>         ctx.save_for_backward(x)
>>>         return x.clone(), x.clone()
>>>
>>>     @staticmethod
>>>     @once_differentiable
>>>     def backward(ctx, g1, g2):
>>>         x, = ctx.saved_tensors
>>>         grad_input = torch.zeros_like(x)
>>>         if g1 is not None:  # We must check for None now
>>>             grad_input += g1
>>>         if g2 is not None:
>>>             grad_input += g2
>>>         return grad_input
>>>
>>> a = torch.tensor(1., requires_grad=True)
>>> b, _ = Func.apply(a)  # induces g2 to be undefined
fovi.arch.knn_bank.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.

fovi.arch.knn_bank.cuda_kernels(device_index: int) → dict[tuple[str, torch.dtype], RawKernel][source]

Compile native CUDA reductions once per device; PyTorch owns the stream.

class fovi.arch.knn_bank.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.

class fovi.arch.knn_bank.Project(*args, **kwargs)[source]

Bases: Function

static forward(ctx: FunctionCtx, x: Tensor, levels: Tensor, bank: IncidenceBank) → Tensor[source]

Define the forward of the custom autograd Function.

This function is to be overridden by all subclasses. There are two ways to define forward:

Usage 1 (Combined forward and ctx):

@staticmethod
def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any:
    pass

Usage 2 (Separate forward and ctx):

@staticmethod
def forward(*args: Any, **kwargs: Any) -> Any:
    pass


@staticmethod
def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None:
    pass
  • The forward no longer accepts a ctx argument.

  • Instead, you must also override the torch.autograd.Function.setup_context() staticmethod to handle setting up the ctx object. output is the output of the forward, inputs are a Tuple of inputs to the forward.

  • See Extending torch.autograd for more details

The context can be used to store arbitrary data that can be then retrieved during the backward pass. Tensors should not be stored directly on ctx (though this is not currently enforced for backward compatibility). Instead, tensors should be saved either with ctx.save_for_backward() if they are intended to be used in backward (equivalently, vjp) or ctx.save_for_forward() if they are intended to be used for in jvp.

static backward(ctx: FunctionCtx, grad: Tensor) → tuple[Tensor, None, None][source]

Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses. (Defining this function is equivalent to defining the vjp function.)

It must accept a context ctx as the first argument, followed by as many outputs as the forward() returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.

The strides of the gradients passed to backward() are undefined: they are not guaranteed to be contiguous or to match the strides of the corresponding forward outputs, so implementations must not assume a particular memory layout.

The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computed w.r.t. the output.