def nearest_neighbors(self, embedding: torch.Tensor, n_neighbors: int) -> tuple[torch.Tensor, torch.Tensor]:
        """Find nearest neighbors in memory bank for input embeddings.

        Uses brute force search with Euclidean distance to find the closest
        matches in the memory bank for each input embedding.

        Args:
            embedding (torch.Tensor): Query embeddings to find neighbors for.
            n_neighbors (int): Number of nearest neighbors to return.

        Returns:
            tuple[torch.Tensor, torch.Tensor]: Tuple containing:
                - Distances to nearest neighbors (shape: ``(n, k)``)
                - Indices of nearest neighbors (shape: ``(n, k)``)
                where ``n`` is number of query embeddings and ``k`` is
                ``n_neighbors``.

        Example:
            >>> embedding = torch.randn(100, 512)
            >>> # Assuming memory_bank is already populated
            >>> scores, locations = model.nearest_neighbors(embedding, n_neighbors=5)
            >>> scores.shape, locations.shape
            (torch.Size([100, 5]), torch.Size([100, 5]))
        """
        distances = self.euclidean_dist(embedding, self.memory_bank)
        if n_neighbors == 1:
            # when n_neighbors is 1, speed up computation by using min instead of topk
            patch_scores, locations = distances.min(1)
        else:
            patch_scores, locations = distances.topk(k=n_neighbors, largest=False, dim=1)
        return patch_scores, locations
Find nearest neighbors in memory bank for input embeddings.

        Uses brute force search with Euclidean distance to find the closest
        matches in the memory bank for each input embedding.

        Args:
            embedding (torch.Tensor): Query embeddings to find neighbors for.
            n_neighbors (int): Number of nearest neighbors to return.

        Returns:
            tuple[torch.Tensor, torch.Tensor]: Tuple containing:
                - Distances to nearest neighbors (shape: ``(n, k)``)
                - Indices of nearest neighbors (shape: ``(n, k)``)
                where ``n`` is number of query embeddings and ``k`` is
                ``n_neighbors``.

        Example:
            >>> embedding = torch.randn(100, 512)
            >>> # Assuming memory_bank is already populated
            >>> scores, locations = model.nearest_neighbors(embedding, n_neighbors=5)
            >>> scores.shape, locations.shape
            (torch.Size([100, 5]), torch.Size([100, 5]))
        
src/anomalib/models/image/patchcore/torch_model.py