fovi.utils package
- fovi.utils.add_to_all(all)[source]
Decorator that adds a function or class name to an __all__ list.
Use this decorator to automatically register module exports.
- Parameters:
all (list) – The __all__ list to append to.
- Returns:
A decorator that appends the function/class name to all.
- Return type:
callable
Example
>>> __all__ = [] >>> @add_to_all(__all__) ... def my_function(): ... pass >>> 'my_function' in __all__ True
- fovi.utils.get_random_name()[source]
generate a random 10-digit string of uppercase and lowercase letters, and digits
- fovi.utils.get_model(model, distributed)[source]
Get the underlying model from a potentially distributed model wrapper.
In distributed training, models are wrapped in DistributedDataParallel, and the actual model is accessible via the .module attribute.
- Parameters:
model (nn.Module) – The model, potentially wrapped in DDP.
distributed (bool) – Whether distributed training is enabled.
- Returns:
The underlying model (unwrapped if distributed).
- Return type:
nn.Module
- fovi.utils.reproducible_results(seed=1)[source]
Set random seeds for reproducible experiments.
Configures PyTorch, NumPy, and CUDA random number generators for reproducibility. Also sets cuDNN to deterministic mode.
- Parameters:
seed (int, optional) – Random seed value. If None, no seeding is done. Defaults to 1.
Note
Setting deterministic mode may reduce performance but ensures reproducibility across runs.
- class fovi.utils.HiddenPrints(enabled=True)[source]
Bases:
objectContext manager to suppress stdout output.
Temporarily redirects stdout to devnull to hide print statements from called functions.
- Parameters:
enabled (bool, optional) – Whether to suppress prints. If False, acts as a no-op. Defaults to True.
Example
>>> with HiddenPrints(): ... print("This won't be shown") >>> print("This will be shown") This will be shown
- fovi.utils.normalize(x, min=None, max=None, dim=None)[source]
Normalize values to [0, 1] range using min-max normalization.
Computes (x - min) / (max - min). If min/max are not provided, they are computed from the data.
- Parameters:
x (torch.Tensor or np.ndarray) – Input values to normalize.
min (float or torch.Tensor, optional) – Minimum value for normalization. If None, computed from x. Defaults to None.
max (float or torch.Tensor, optional) – Maximum value for normalization. If None, computed from x. Defaults to None.
dim (int, optional) – Dimension along which to compute min/max. If None, uses global min/max. Defaults to None.
- Returns:
- Normalized values in [0, 1] range.
Returns same type as input.
- Return type:
torch.Tensor or np.ndarray
- fovi.utils.timeit(description='Code block')[source]
Context manager that times and prints the execution duration of a code block.
- Parameters:
description (str, optional) – Label to print with the timing. Defaults to “Code block”.
Example
>>> with timeit("My operation"): ... time.sleep(1) My operation: 1.00... seconds
- fovi.utils.load_pretrained(model, weights, progress)[source]
Load pretrained weights into a model.
- Parameters:
model (nn.Module) – The model to load weights into.
weights – Pretrained weights object with a get_state_dict method (e.g., from torchvision.models).
progress (bool) – Whether to display a progress bar during download.
- Returns:
The model with loaded weights.
- Return type:
nn.Module
- fovi.utils.analyze_rf(points, rf_center=None)[source]
Analyze receptive field (RF) for geometric properties.
Fits an ellipse to the RF boundary points and computes metrics describing the RF shape and position.
- Parameters:
points (torch.Tensor or np.ndarray) – Array of shape (N, 2) containing the (x, y) coordinates of RF boundary points.
rf_center (tuple, optional) – (x, y) coordinates of the RF center. If None, uses the first point as the center. Defaults to None.
- Returns:
- A tuple (area, aspect_ratio, radial_displacement) where:
area (float): Area of the fitted ellipse (pi * a * b).
aspect_ratio (float): Ratio of semi-minor to semi-major axis (b/a).
radial_displacement (float): Normalized radial displacement of the center from the ellipse center, in range [0, 2].
- Return type:
- fovi.utils.normalize_imagenet(x)[source]
Normalize an image using ImageNet mean and standard deviation.
Applies the standard ImageNet normalization: (x - mean) / std.
- Parameters:
x (np.ndarray) – Image array to normalize.
- Returns:
Normalized image array.
- Return type:
np.ndarray
- fovi.utils.flatten_dict(d, prefix='', separator='.')[source]
Flatten a nested dictionary into a single-level dictionary.
Nested keys are joined with the separator to form compound keys.
- Parameters:
- Returns:
Flattened dictionary with compound keys.
- Return type:
Example
>>> flatten_dict({'a': {'b': 1, 'c': 2}, 'd': 3}) {'a.b': 1, 'a.c': 2, 'd': 3}
- fovi.utils.unflatten_dict(d, separator='.')[source]
Unflatten a dictionary with compound keys into a nested dictionary.
Inverse operation of flatten_dict. Splits compound keys on the separator to reconstruct nested structure.
- Parameters:
- Returns:
Nested dictionary structure.
- Return type:
Example
>>> unflatten_dict({'a.b': 1, 'a.c': 2, 'd': 3}) {'a': {'b': 1, 'c': 2}, 'd': 3}
Subpackages
Modules
- fovi.utils.fastaugs.functional
radians()set_trace()mask_batch()mask_tensor()normalize()to_device()to_numpy()to_float()div_()to_channels_first()to_channels_last()random_grayscale()to_grayscale()dummy_red()mat3()hue_mat()sat_mat()val_mat()hsv_mat()hsv_mat2()hsv_jitter_tensor()hsv_jitter_array()hsv_jitter_array2()hsv_jitter()hsv_jitter2()random_hsv_jitter2()_get_scale_factor()adjust_brightness()adjust_brightness_pil()sigmoid()logit()random_adjust_brightness()adjust_contrast()adjust_contrast_logit()adjust_contrast_pil()adjust_rms_contrast()adjust_rms_contrast_logit()random_adjust_contrast()_prepare_mat()_grid_sample()affine_transform()flip_mat()_prepare_thetas()_prepare_coords()_prepare_rot_pt()_prepare_param()rotate_mat()rotate()zoom_mat()zoom()translate_mat()rotate_object_mat()rotate_object()grid_sample()random_grid_sample()apply_mask()srgb_to_lrgb()rgb_to_xyz()xyz_to_lms()srgb_to_lms()lms_to_lgrby()crop()solarization()random_solarization()random_gaussian_blur2d()generate_batch_permutations()to_torch_image()
- fovi.utils.fastaugs.functional_tensor
TensorTensor._clear_non_serializable_cached_data()Tensor.align_to()Tensor.backward()Tensor.detach()Tensor.detach_()Tensor.dim_order()Tensor.eig()Tensor.index()Tensor.is_shared()Tensor.istft()Tensor.lstsq()Tensor.lu()Tensor.module_load()Tensor.norm()Tensor.refine_names()Tensor.register_hook()Tensor.register_post_accumulate_grad_hook()Tensor.reinforce()Tensor.rename()Tensor.rename_()Tensor.resize()Tensor.resize_as()Tensor.share_memory_()Tensor.solve()Tensor.split()Tensor.stft()Tensor.storage()Tensor.storage_type()Tensor.symeig()Tensor.to_sparse_coo()Tensor.unflatten()Tensor.unique()Tensor.unique_consecutive()
grid_sample()conv2d()interpolate()torch_pad()get_image_size()get_image_num_channels()convert_image_dtype()vflip()hflip()crop()rgb_to_grayscale()adjust_brightness()adjust_contrast()adjust_hue()adjust_hue_fast()adjust_saturation()mat3()_get_sbc_mat()color_jitter()random_color_jitter()adjust_gamma()center_crop()five_crop()ten_crop()pad()resize()affine()rotate()perspective()gaussian_blur()invert()posterize()solarize()adjust_sharpness()autocontrast()equalize()
- fovi.utils.fastaugs.loader
- fovi.utils.fastaugs.transforms
ComposeRandomApplyToTorchImageToNumpyToChannelsFirstToChannelsLastToDeviceToFloatToFloatDivMultiSampleNormalizeGPUCircularMaskToGrayscaleTorchGPUToGrayscaleGPUColorJitterRandomGaussianBlurRandomHorizontalFlipRandomGrayscaleRandomBrightnessRandomContrastRandomSolarizationRandomRotateRandomZoomRandomPatchShuffleRandomColorJitterYIQRandomColorJitterRandomRotateObject
- fovi.utils.flops
- fovi.utils.image
- fovi.utils.knnprobe
- fovi.utils.lora
- fovi.utils.losses
- fovi.utils.lr_scheduling
- fovi.utils.std_transforms