Source code for kempnerforge.config.vision
"""Vision-encoder configuration.
``VisionEncoderConfig`` selects and parameterizes the vision encoder
that the ``VLMWrapper`` composes alongside the text backbone and
adapter. It is a top-level section in TOML (``[vision_encoder]``),
sibling to ``[model]``, ``[adapter]``, and ``[vlm]``.
Field summary:
- ``type`` selects the encoder by registry key
(see ``registry.register_vision_encoder``). Defaults to ``"random"``
for tests; production configs set ``"siglip2"`` / ``"clip"`` etc.
- ``path`` is the HF Hub id or local path passed to the encoder
builder. Empty string is accepted for stub encoders (``"random"``);
``JobConfig.validate`` refuses it for the HF-backed ``"siglip2"`` and
``"clip"``.
- ``feature_dim`` is the output feature dim of the encoder. ``0`` means
"infer from the encoder at build time"; an HF-backed encoder reads its
model config's ``hidden_size``, and its build raises when that is
missing, asking for ``feature_dim``.
- ``num_tokens`` is the number of image tokens the encoder produces per
image. ``0`` means "infer at build time". When ``> 0`` it is cross-
checked against ``model.max_seq_len`` at config time inside
``JobConfig.__post_init__``.
- ``mixed_precision`` is the dtype the encoder computes in (``"bf16"`` or
``"fp32"``), independent of ``train.mixed_precision``, for image and video
runs alike, also under the ``torch.autocast`` that
``train.fp32_master_weights`` runs without an FSDP2 wrap. Its parameters,
gradients and optimizer state keep the dtype the encoder was loaded in, on
any number of GPUs. Its floating-point buffers are cast to the set dtype,
so a checkpoint holds them in it. Unset, the encoder keeps the default:
an FSDP2-wrapped encoder computes in the language model's dtype, and an
unwrapped one in its loaded dtype, with that autocast reaching its
matmuls where it runs. It applies to the training build
(``build_parallel_model``); ``build_vlm_wrapper`` leaves every dtype to
its caller.
- ``grad_reduce_dtype`` is the dtype FSDP2 reduces the encoder's gradients in
(``"fp32"``, the default, or ``"bf16"``), set apart from
``train.grad_reduce_dtype`` and from ``mixed_precision``: a bf16 reduce of an
encoder that computes in fp32 rounds its gradients to bf16 for the reduce
only. With ``"bf16"`` the encoder's unit syncs on every micro-step (see
``kempnerforge.training.grad.maybe_no_sync``), so gradients are accumulated
and stepped in the encoder's parameter dtype either way. ``"bf16"`` is refused
where the encoder is not FSDP2-wrapped: by ``JobConfig.validate`` without a
data-parallel mesh, and at build when no step of the run trains it.
- ``drop_pooling_head`` removes a SigLIP tower's attention-pooling head, which
HF runs for a pooled output the encoder never returns. Only an encoder whose
builder declares a ``drop_pooling_head`` parameter takes it (``siglip2``);
any other type is refused here. A checkpoint saved with the head loads into
a model built without it, since the head's tensors are not requested; one
saved without the head does not load into a model that has it.
"""
from __future__ import annotations
import inspect
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal
from kempnerforge.config.registry import registry
if TYPE_CHECKING:
import torch
[docs]
@dataclass
class VisionEncoderConfig:
"""Configuration for the vision encoder component of a VLM.
``drop_pooling_head`` removes a SigLIP tower's attention-pooling head, whose
pooled output the encoder never returns; the encoder's builder must declare it.
"""
type: str = "random"
path: str = ""
feature_dim: int = 0
num_tokens: int = 0
mixed_precision: Literal["bf16", "fp32"] | None = None
grad_reduce_dtype: Literal["fp32", "bf16"] = "fp32"
drop_pooling_head: bool = False
def __post_init__(self) -> None:
import kempnerforge.model.vision # noqa: F401, PLC0415
registered = tuple(registry.list_vision_encoders())
if self.type not in registered:
raise ValueError(
f"Unknown vision_encoder.type: {self.type!r}. Registered: {sorted(registered)}."
)
if self.feature_dim < 0:
raise ValueError(
f"vision_encoder.feature_dim must be non-negative (got {self.feature_dim})"
)
if self.num_tokens < 0:
raise ValueError(
f"vision_encoder.num_tokens must be non-negative (got {self.num_tokens})"
)
if self.mixed_precision not in (None, "bf16", "fp32"):
raise ValueError(
"vision_encoder.mixed_precision must be one of ['bf16', 'fp32'] "
f"or unset (got {self.mixed_precision!r})"
)
if self.grad_reduce_dtype not in ("fp32", "bf16"):
raise ValueError(
"vision_encoder.grad_reduce_dtype must be one of ['fp32', 'bf16'] "
f"(got {self.grad_reduce_dtype!r})"
)
if self.drop_pooling_head and not _declares_drop_pooling_head(
registry.get_vision_encoder(self.type)
):
raise ValueError(
f"vision_encoder.type = {self.type!r} cannot drop a pooling head: its builder "
"declares no drop_pooling_head parameter. Leave drop_pooling_head = false."
)
@property
def compute_dtype(self) -> torch.dtype | None:
"""The dtype the encoder computes in, or ``None`` when ``mixed_precision`` is unset."""
if self.mixed_precision is None:
return None
import torch
return {"bf16": torch.bfloat16, "fp32": torch.float32}[self.mixed_precision]
@property
def reduce_dtype(self) -> torch.dtype:
"""Dtype FSDP2 reduces the encoder's gradients in."""
import torch
return {"bf16": torch.bfloat16, "fp32": torch.float32}[self.grad_reduce_dtype]
def _declares_drop_pooling_head(builder: Callable[..., Any]) -> bool:
"""Whether ``builder`` names a ``drop_pooling_head`` parameter passable by keyword."""
parameter = inspect.signature(builder, follow_wrapped=False).parameters.get("drop_pooling_head")
return parameter is not None and parameter.kind in (
inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.KEYWORD_ONLY,
)