콘텐츠로 이동

Component API Reference

dataset

Dataset

Bases: Dataset

Base class for all CVLab-Kit datasets.

This class uses InterfaceMeta to act as a wrapper around a PyTorch Dataset instance. Subclasses should define a dataset attribute in their __init__ method, which will be the target for attribute and method delegation.

Source code in cvlabkit/component/base/dataset.py
class Dataset(TorchDataset, metaclass=InterfaceMeta):
    """Base class for all CVLab-Kit datasets.

    This class uses `InterfaceMeta` to act as a wrapper around a PyTorch
    `Dataset` instance. Subclasses should define a `dataset` attribute
    in their `__init__` method, which will be the target for attribute and
    method delegation.
    """

    @abstractmethod
    def __getitem__(self, index) -> Any:
        """Retrieves the item at the given index.

        Args:
            index (int): The index of the item to retrieve.

        Returns:
            Any: The item at the specified index.
        """
        pass

    @abstractmethod
    def __len__(self) -> int:
        """Returns the total number of items in the dataset.

        Returns:
            int: The total number of items.
        """
        pass

__getitem__ abstractmethod

Retrieves the item at the given index.

Parameters:

Name Type Description Default
index int

The index of the item to retrieve.

required

Returns:

Name Type Description
Any Any

The item at the specified index.

Source code in cvlabkit/component/base/dataset.py
@abstractmethod
def __getitem__(self, index) -> Any:
    """Retrieves the item at the given index.

    Args:
        index (int): The index of the item to retrieve.

    Returns:
        Any: The item at the specified index.
    """
    pass

__len__ abstractmethod

Returns the total number of items in the dataset.

Returns:

Name Type Description
int int

The total number of items.

Source code in cvlabkit/component/base/dataset.py
@abstractmethod
def __len__(self) -> int:
    """Returns the total number of items in the dataset.

    Returns:
        int: The total number of items.
    """
    pass

data_loader

DataLoader

Bases: DataLoader

Base class for all CVLab-Kit data loaders.

This class uses InterfaceMeta to act as a wrapper around a PyTorch DataLoader instance. Subclasses should define a loader attribute in their __init__ method, which will be the target for attribute and method delegation.

Source code in cvlabkit/component/base/data_loader.py
class DataLoader(TorchDataLoader, metaclass=InterfaceMeta):
    """Base class for all CVLab-Kit data loaders.

    This class uses `InterfaceMeta` to act as a wrapper around a PyTorch
    `DataLoader` instance. Subclasses should define a `loader` attribute
    in their `__init__` method, which will be the target for attribute and
    method delegation.
    """

    @abstractmethod
    def __iter__(self) -> Iterator:
        """Returns an iterator over the dataset."""
        pass

    @abstractmethod
    def __len__(self) -> int:
        """Returns the number of batches in the data loader."""
        pass

__iter__ abstractmethod

Returns an iterator over the dataset.

Source code in cvlabkit/component/base/data_loader.py
@abstractmethod
def __iter__(self) -> Iterator:
    """Returns an iterator over the dataset."""
    pass

__len__ abstractmethod

Returns the number of batches in the data loader.

Source code in cvlabkit/component/base/data_loader.py
@abstractmethod
def __len__(self) -> int:
    """Returns the number of batches in the data loader."""
    pass

model

Model

Bases: Module

Abstract base class for all models.

Source code in cvlabkit/component/base/model.py
class Model(torch.nn.Module, metaclass=InterfaceMeta):
    """Abstract base class for all models."""

    @abstractmethod
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Defines the forward pass of the model.

        Args:
            x (torch.Tensor): The input tensor.

        Returns:
            torch.Tensor: The output tensor.
        """
        pass

forward abstractmethod

Defines the forward pass of the model.

Parameters:

Name Type Description Default
x Tensor

The input tensor.

required

Returns:

Type Description
Tensor

torch.Tensor: The output tensor.

Source code in cvlabkit/component/base/model.py
@abstractmethod
def forward(self, x: torch.Tensor) -> torch.Tensor:
    """Defines the forward pass of the model.

    Args:
        x (torch.Tensor): The input tensor.

    Returns:
        torch.Tensor: The output tensor.
    """
    pass

loss

Loss

Bases: Module

Abstract base class for all loss functions.

This class defines the interface for loss components. When implementing a custom loss, the forward method should be defined to accept the necessary tensors. The framework distinguishes between losses based on the number of arguments their forward method accepts.

Source code in cvlabkit/component/base/loss.py
class Loss(torch.nn.Module, metaclass=InterfaceMeta):
    """Abstract base class for all loss functions.

    This class defines the interface for loss components. When implementing a custom
    loss, the `forward` method should be defined to accept the necessary tensors.
    The framework distinguishes between losses based on the number of arguments
    their `forward` method accepts.
    """

    @abstractmethod
    def forward(self, *inputs: torch.Tensor) -> torch.Tensor:
        """Computes the loss based on a variable number of input tensors.

        The number and order of tensors depend on the specific loss function being
        implemented.

        Args:
            *inputs (torch.Tensor): A sequence of tensors required for the loss
                computation. Common patterns include:
                - `(predictions, targets)`: For standard losses like Cross-Entropy.
                - `(anchor, positive, negative)`: For triplet-based losses.
                - `(student_preds, teacher_preds, targets)`: For knowledge distillation.

        Returns:
            torch.Tensor: A scalar tensor representing the computed loss value.
        """
        raise NotImplementedError

forward abstractmethod

Computes the loss based on a variable number of input tensors.

The number and order of tensors depend on the specific loss function being implemented.

Parameters:

Name Type Description Default
*inputs Tensor

A sequence of tensors required for the loss computation. Common patterns include: - (predictions, targets): For standard losses like Cross-Entropy. - (anchor, positive, negative): For triplet-based losses. - (student_preds, teacher_preds, targets): For knowledge distillation.

()

Returns:

Type Description
Tensor

torch.Tensor: A scalar tensor representing the computed loss value.

Source code in cvlabkit/component/base/loss.py
@abstractmethod
def forward(self, *inputs: torch.Tensor) -> torch.Tensor:
    """Computes the loss based on a variable number of input tensors.

    The number and order of tensors depend on the specific loss function being
    implemented.

    Args:
        *inputs (torch.Tensor): A sequence of tensors required for the loss
            computation. Common patterns include:
            - `(predictions, targets)`: For standard losses like Cross-Entropy.
            - `(anchor, positive, negative)`: For triplet-based losses.
            - `(student_preds, teacher_preds, targets)`: For knowledge distillation.

    Returns:
        torch.Tensor: A scalar tensor representing the computed loss value.
    """
    raise NotImplementedError

optimizer

Optimizer

Bases: Optimizer

Abstract base class for all optimizers.

Source code in cvlabkit/component/base/optimizer.py
class Optimizer(TorchOptimizer, metaclass=InterfaceMeta):
    """Abstract base class for all optimizers."""

    @abstractmethod
    def step(self) -> None:
        """Performs a single optimization step."""
        pass

    @abstractmethod
    def zero_grad(self) -> None:
        """Clears the gradients of all optimized `torch.Tensor`s."""
        pass

step abstractmethod

Performs a single optimization step.

Source code in cvlabkit/component/base/optimizer.py
@abstractmethod
def step(self) -> None:
    """Performs a single optimization step."""
    pass

zero_grad abstractmethod

Clears the gradients of all optimized torch.Tensors.

Source code in cvlabkit/component/base/optimizer.py
@abstractmethod
def zero_grad(self) -> None:
    """Clears the gradients of all optimized `torch.Tensor`s."""
    pass

transform

Transform

Abstract base class for all transforms.

Source code in cvlabkit/component/base/transform.py
class Transform(metaclass=InterfaceMeta):
    """Abstract base class for all transforms."""

    @abstractmethod
    def __call__(self, sample: Any) -> Any:
        """Applies the transform to the given sample.

        Args:
            sample (Any): The input data to transform.

        Returns:
            Any: The transformed data.
        """
        pass

__call__ abstractmethod

Applies the transform to the given sample.

Parameters:

Name Type Description Default
sample Any

The input data to transform.

required

Returns:

Name Type Description
Any Any

The transformed data.

Source code in cvlabkit/component/base/transform.py
@abstractmethod
def __call__(self, sample: Any) -> Any:
    """Applies the transform to the given sample.

    Args:
        sample (Any): The input data to transform.

    Returns:
        Any: The transformed data.
    """
    pass

metric

Metric

Abstract base class for all metrics.

Source code in cvlabkit/component/base/metric.py
class Metric(metaclass=InterfaceMeta):
    """Abstract base class for all metrics."""

    @abstractmethod
    def update(self, **kwargs: Any) -> None:
        """Updates the metric's internal state with new data.

        Args:
            **kwargs: Arbitrary keyword arguments representing the data to update the metric.
        """
        pass

    @abstractmethod
    def compute(self) -> Dict[str, float]:
        """Computes the final metric value(s).

        Returns:
            Dict[str, float]: A dictionary of metric names and their computed values.
        """
        pass

    @abstractmethod
    def reset(self) -> None:
        """Resets the metric's internal state."""
        pass

update abstractmethod

Updates the metric's internal state with new data.

Parameters:

Name Type Description Default
**kwargs Any

Arbitrary keyword arguments representing the data to update the metric.

{}
Source code in cvlabkit/component/base/metric.py
@abstractmethod
def update(self, **kwargs: Any) -> None:
    """Updates the metric's internal state with new data.

    Args:
        **kwargs: Arbitrary keyword arguments representing the data to update the metric.
    """
    pass

compute abstractmethod

Computes the final metric value(s).

Returns:

Type Description
dict[str, float]

Dict[str, float]: A dictionary of metric names and their computed values.

Source code in cvlabkit/component/base/metric.py
@abstractmethod
def compute(self) -> Dict[str, float]:
    """Computes the final metric value(s).

    Returns:
        Dict[str, float]: A dictionary of metric names and their computed values.
    """
    pass

reset abstractmethod

Resets the metric's internal state.

Source code in cvlabkit/component/base/metric.py
@abstractmethod
def reset(self) -> None:
    """Resets the metric's internal state."""
    pass

checkpoint

Checkpoint

Abstract base class for checkpointing functionalities.

Source code in cvlabkit/component/base/checkpoint.py
class Checkpoint(metaclass=InterfaceMeta):
    """Abstract base class for checkpointing functionalities."""

    @abstractmethod
    def save(self, state: Dict[str, Any], file_path: str) -> None:
        """Saves the current state of the experiment.

        Args:
            state (Dict[str, Any]): The state dictionary to save.
            file_path (str): The path to the file where the state will be saved.
        """
        pass

    @abstractmethod
    def load(self, file_path: str) -> None:
        """Loads a previously saved state.

        Args:
            file_path (str): The path to the file from which the state will be loaded.
        """
        pass

save abstractmethod

Saves the current state of the experiment.

Parameters:

Name Type Description Default
state dict[str, Any]

The state dictionary to save.

required
file_path str

The path to the file where the state will be saved.

required
Source code in cvlabkit/component/base/checkpoint.py
@abstractmethod
def save(self, state: Dict[str, Any], file_path: str) -> None:
    """Saves the current state of the experiment.

    Args:
        state (Dict[str, Any]): The state dictionary to save.
        file_path (str): The path to the file where the state will be saved.
    """
    pass

load abstractmethod

Loads a previously saved state.

Parameters:

Name Type Description Default
file_path str

The path to the file from which the state will be loaded.

required
Source code in cvlabkit/component/base/checkpoint.py
@abstractmethod
def load(self, file_path: str) -> None:
    """Loads a previously saved state.

    Args:
        file_path (str): The path to the file from which the state will be loaded.
    """
    pass

scheduler

Scheduler

Bases: _LRScheduler

Abstract base class for all learning rate schedulers.

Source code in cvlabkit/component/base/scheduler.py
class Scheduler(_LRScheduler, metaclass=InterfaceMeta):
    """Abstract base class for all learning rate schedulers."""

    @abstractmethod
    def step(self) -> None:
        """Performs a single learning rate update step."""
        pass

step abstractmethod

Performs a single learning rate update step.

Source code in cvlabkit/component/base/scheduler.py
@abstractmethod
def step(self) -> None:
    """Performs a single learning rate update step."""
    pass

sampler

Sampler

Bases: Sampler

Abstract base class for data samplers.

Source code in cvlabkit/component/base/sampler.py
class Sampler(TorchSampler, metaclass=InterfaceMeta):
    """Abstract base class for data samplers."""

    @abstractmethod
    def __iter__(self) -> Iterator[int]:
        """Returns an iterator that yields the indices of samples."""
        pass

    @abstractmethod
    def __len__(self) -> int:
        """Returns the total number of samples to be drawn."""
        pass

__iter__ abstractmethod

Returns an iterator that yields the indices of samples.

Source code in cvlabkit/component/base/sampler.py
@abstractmethod
def __iter__(self) -> Iterator[int]:
    """Returns an iterator that yields the indices of samples."""
    pass

__len__ abstractmethod

Returns the total number of samples to be drawn.

Source code in cvlabkit/component/base/sampler.py
@abstractmethod
def __len__(self) -> int:
    """Returns the total number of samples to be drawn."""
    pass

logger

Logger

Abstract base class for all loggers.

Source code in cvlabkit/component/base/logger.py
class Logger(metaclass=InterfaceMeta):
    """Abstract base class for all loggers."""

    @abstractmethod
    def log_metrics(self, metrics: Dict[str, float], step: int) -> None:
        """Logs a dictionary of metrics at a given step.

        Args:
            metrics (Dict[str, float]): A dictionary of metric names and their values.
            step (int): The current step or epoch number.
        """
        pass

    @abstractmethod
    def log_hyperparams(self, params: Dict[str, Any]) -> None:
        """Logs a dictionary of hyperparameters.

        Args:
            params (Dict[str, Any]): A dictionary of hyperparameter names and their values.
        """
        pass

    @abstractmethod
    def finalize(self) -> None:
        """Finalizes the logging process, e.g., closes connections or saves data."""
        pass

log_metrics abstractmethod

Logs a dictionary of metrics at a given step.

Parameters:

Name Type Description Default
metrics dict[str, float]

A dictionary of metric names and their values.

required
step int

The current step or epoch number.

required
Source code in cvlabkit/component/base/logger.py
@abstractmethod
def log_metrics(self, metrics: Dict[str, float], step: int) -> None:
    """Logs a dictionary of metrics at a given step.

    Args:
        metrics (Dict[str, float]): A dictionary of metric names and their values.
        step (int): The current step or epoch number.
    """
    pass

log_hyperparams abstractmethod

Logs a dictionary of hyperparameters.

Parameters:

Name Type Description Default
params dict[str, Any]

A dictionary of hyperparameter names and their values.

required
Source code in cvlabkit/component/base/logger.py
@abstractmethod
def log_hyperparams(self, params: Dict[str, Any]) -> None:
    """Logs a dictionary of hyperparameters.

    Args:
        params (Dict[str, Any]): A dictionary of hyperparameter names and their values.
    """
    pass

finalize abstractmethod

Finalizes the logging process, e.g., closes connections or saves data.

Source code in cvlabkit/component/base/logger.py
@abstractmethod
def finalize(self) -> None:
    """Finalizes the logging process, e.g., closes connections or saves data."""
    pass

solver

Solver

Abstract base class for differential equation solvers.

Solvers are used for ODE/SDE integration in generative models, neural ODEs, and other continuous-time systems.

Source code in cvlabkit/component/base/solver.py
class Solver(metaclass=InterfaceMeta):
    """Abstract base class for differential equation solvers.

    Solvers are used for ODE/SDE integration in generative models,
    neural ODEs, and other continuous-time systems.
    """

    @abstractmethod
    def __call__(self, *args, **kwargs):
        """Solve differential equation.

        Args:
            *args, **kwargs: Solver-specific inputs

        Returns:
            Solution of the differential equation
        """
        pass

__call__ abstractmethod

Solve differential equation.

Parameters:

Name Type Description Default
*args, **kwargs

Solver-specific inputs

required

Returns:

Type Description

Solution of the differential equation

Source code in cvlabkit/component/base/solver.py
@abstractmethod
def __call__(self, *args, **kwargs):
    """Solve differential equation.

    Args:
        *args, **kwargs: Solver-specific inputs

    Returns:
        Solution of the differential equation
    """
    pass