Backbone API¶
Interfaces and contracts¶
interfaces
¶
Capability-based interfaces for vision-language backbones.
The papers in :mod:methods do not all consume the same kind of encoder.
Some need a black-box text encoder, some inject learnable tokens into a text
transformer, and SLDPC needs a paired slide projector and promptable text
tower. A single (model, tokenizer) tuple cannot express those
differences safely.
This module deliberately keeps the interfaces narrow. Vendor-specific wrappers implement them while method code keeps ownership of the published architecture. In particular, compatibility never implies that an unpublished alignment projection may be inserted between unrelated models.
BackboneCompatibilityError
¶
Bases: ValueError
Raised before model construction when an encoder contract is unmet.
BackboneCapability
¶
Bases: str, Enum
Small, independently testable encoder capabilities.
FeatureLevel
¶
Bases: str, Enum
The tensor level at which a method meets its encoder.
SwapPolicy
¶
Bases: str, Enum
How broadly a method can accept another encoder implementation.
TokenBatch
dataclass
¶
TokenBatch(
input_ids: Tensor,
attention_mask: Optional[Tensor] = None,
eot_indices: Optional[Tensor] = None,
extras: Mapping[str, Tensor] = dict(),
)
Tokenizer output with explicit masks and pooling positions.
extras preserves vendor fields such as token_type_ids without
making every consumer depend on a Hugging Face BatchEncoding.
to
¶
Return a copy with every tensor moved to device.
Source code in common/backbones/interfaces.py
as_kwargs
¶
Convert the batch to keyword arguments accepted by text models.
Source code in common/backbones/interfaces.py
BackboneSpec
dataclass
¶
BackboneSpec(
name: str,
family: str,
feature_space_id: str,
capabilities: FrozenSet[BackboneCapability],
revision: Optional[str] = None,
tile_dim: Optional[int] = None,
slide_input_dim: Optional[int] = None,
vision_token_dim: Optional[int] = None,
text_token_dim: Optional[int] = None,
shared_dim: Optional[int] = None,
context_length: Optional[int] = None,
image_size: Optional[int] = None,
aliases: Tuple[str, ...] = (),
)
Record dimensions and provenance needed to judge a backbone swap.
Capabilities describe operations exposed by the runtime bundle. Dimension
fields refer to native encoder boundaries; shared_dim is the paired
comparison space when one exists.
has
¶
has(*capabilities: BackboneCapability) -> bool
Return whether the spec declares every requested capability.
TextEncoder
¶
Bases: Protocol
Black-box text encoding in the model's native shared space.
tokenize
¶
tokenize(texts: Sequence[str]) -> TokenBatch
encode_text
¶
PromptableTextEncoder
¶
Bases: TextEncoder, Protocol
Text tower that supports differentiable embedded soft prompts.
embed_tokens
¶
embed_tokens(tokens: TokenBatch) -> Tensor
encode_embedded
¶
encode_embedded(
embeddings: Tensor,
tokens: TokenBatch,
normalize: bool = True,
) -> Tensor
Encode pre-embedded prompt tokens into the paired shared space.
tokenize
¶
tokenize(texts: Sequence[str]) -> TokenBatch
encode_text
¶
TileEncoder
¶
SlideProjector
¶
EncoderBundle
dataclass
¶
EncoderBundle(
raw_model: Module,
spec: BackboneSpec,
raw_tokenizer: Any = None,
text: Optional[TextEncoder] = None,
tile: Optional[TileEncoder] = None,
slide: Optional[SlideProjector] = None,
preprocess: Optional[Callable[..., Any]] = None,
metadata: Mapping[str, Any] = dict(),
)
Uniform runtime handle while retaining access to the native objects.
raw_model and raw_tokenizer are intentional escape hatches for
paper implementations that traverse a specific transformer's layers.
Capability validation must happen before those objects are passed on.
tokenizer
property
¶
Return the native tokenizer (migration alias for raw_tokenizer).
require
¶
require(
*capabilities: BackboneCapability,
consumer: Optional[str] = None,
) -> "EncoderBundle"
Assert that this bundle advertises the requested operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*capabilities
|
BackboneCapability
|
Operations required by the caller. |
()
|
consumer
|
Optional[str]
|
Optional name included in validation errors. |
None
|
Returns:
| Type | Description |
|---|---|
'EncoderBundle'
|
This bundle, enabling fluent validation. |
Raises:
| Type | Description |
|---|---|
BackboneCompatibilityError
|
If any capability is absent. |
Source code in common/backbones/interfaces.py
freeze
¶
Put the native model in evaluation mode and disable gradients.
encode_text
¶
Encode text using the bundle's validated text wrapper.
Raises:
| Type | Description |
|---|---|
BackboneCompatibilityError
|
If text encoding is unavailable or the spec declares it without providing a wrapper. |
Source code in common/backbones/interfaces.py
project_slide
¶
Apply the bundle's native slide projector.
Raises:
| Type | Description |
|---|---|
BackboneCompatibilityError
|
If native slide projection is absent. |
Source code in common/backbones/interfaces.py
assert_feature_space
¶
assert_feature_space(
*,
feature_space_id: Optional[str] = None,
dimension: Optional[int] = None,
level: FeatureLevel = PATCH_BAG,
) -> None
Validate cached feature provenance and width against the spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature_space_id
|
Optional[str]
|
Exact producer/checkpoint identity, when known. |
None
|
dimension
|
Optional[int]
|
Last dimension of the cached feature tensor. |
None
|
level
|
FeatureLevel
|
Tensor level used to select tile versus slide dimensions. |
PATCH_BAG
|
Raises:
| Type | Description |
|---|---|
BackboneCompatibilityError
|
If provenance or width differs. |
Source code in common/backbones/interfaces.py
MethodBackboneContract
dataclass
¶
MethodBackboneContract(
method: str,
feature_level: FeatureLevel,
swap_policy: SwapPolicy,
required_capabilities: FrozenSet[
BackboneCapability
] = frozenset(),
config_key: Optional[str] = "backbone",
default_backbone: Optional[str] = None,
supported_backbones: Tuple[str, ...] = (),
name_aliases: Mapping[str, str] = dict(),
feature_dims: Mapping[str, Tuple[int, ...]] = dict(),
feature_boundaries: Mapping[
str, Mapping[str, Tuple[int, ...]]
] = dict(),
feature_dim_key: Optional[str] = "feature_dim",
feature_space_key: Optional[str] = "feature_space_id",
bundle_feature_space_key: Optional[str] = None,
enforce_native_dimension: bool = False,
require_feature_space: bool = False,
rationale: str = "",
)
Declare the encoder and feature boundary accepted by a method.
swap_policy distinguishes architectural compatibility from mere tensor
shape compatibility. Allowlisted, fixed, and precomputed methods must name
a supported native family; capability-based methods validate operations on
the returned bundle.
resolve_name
¶
Resolve and canonicalize the backbone selected by a run config.
Source code in common/backbones/interfaces.py
validate_config
¶
Validate config-only constraints before allocating model weights.
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The canonical selected backbone, or |
Optional[str]
|
no runtime encoder name. |
Raises:
| Type | Description |
|---|---|
BackboneCompatibilityError
|
If the name, width, provenance, or required config fields violate this contract. |
Source code in common/backbones/interfaces.py
validate_bundle
¶
validate_bundle(
cfg: Mapping[str, Any], bundle: EncoderBundle
) -> EncoderBundle
Validate a loaded bundle against this contract and run config.
Returns:
| Type | Description |
|---|---|
EncoderBundle
|
The validated bundle. |
Raises:
| Type | Description |
|---|---|
BackboneCompatibilityError
|
If capabilities, identity, dimensions, or feature provenance are incompatible. |
Source code in common/backbones/interfaces.py
as_dict
¶
Serialize the contract to JSON-compatible registry metadata.
Source code in common/backbones/interfaces.py
canonical_backbone_name
¶
Normalize config spellings without erasing meaningful model families.
normalize_features
¶
Convert features to float and optionally L2-normalize the last axis.
Registry and builders¶
factory
¶
Backbone registry and vendor adapters.
build_backbone retains the historical (model, tokenizer, info)
return value. New code should use :func:build_encoder, whose
:class:~common.backbones.interfaces.EncoderBundle exposes explicit
capabilities and feature-space provenance.
BackboneInfo
dataclass
¶
BackboneInfo(
name: str,
patch_dim: int,
text_dim: int,
image_size: int = 224,
is_clip_compatible: bool = True,
)
Backward-compatible metadata returned by build_backbone.
patch_dim and text_dim are the projected comparison-space
dimensions. Use :class:BackboneSpec when token widths or raw slide
dimensions matter.
TitanPromptableText
¶
Expose TITAN's text tower through the promptable-text protocol.
The wrapper preserves TITAN's native tokenizer, end-of-text pooling, token width, dtype, and paired projection. SLDPC uses it to optimize context embeddings without replacing the native text tower.
Source code in common/backbones/factory.py
list_backbones
¶
get_spec
¶
get_spec(name: str) -> BackboneSpec
Return immutable capability and provenance metadata for an encoder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Canonical encoder name or registered alias. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no matching encoder is registered. |
Source code in common/backbones/factory.py
get_info
¶
get_info(name: str) -> BackboneInfo
register_backbone
¶
register_backbone(
spec: BackboneSpec,
builder: EncoderBuilder,
*,
overwrite: bool = False,
) -> None
Register an encoder bundle without modifying any method architecture.
A builder receives the same keyword arguments as :func:build_encoder
and must return a bundle whose spec.name matches spec.name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
BackboneSpec
|
Immutable metadata for the new encoder. |
required |
builder
|
EncoderBuilder
|
Callable returning a compatible :class: |
required |
overwrite
|
bool
|
Whether to replace an existing registration deliberately. |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the name already exists and |
ValueError
|
If |
Source code in common/backbones/factory.py
unregister_backbone
¶
Remove a process-local custom registration.
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
Source code in common/backbones/factory.py
build_encoder
¶
build_encoder(
name: str,
weights_path: Optional[str] = None,
device: str = "cuda",
**kwargs: Any,
) -> EncoderBundle
Load a capability-aware encoder bundle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Canonical encoder name or alias. |
required |
weights_path
|
Optional[str]
|
Optional local checkpoint, snapshot, or model identifier. |
None
|
device
|
str
|
PyTorch device on which to construct the native model. |
'cuda'
|
**kwargs
|
Any
|
Family-specific loader options. TITAN accepts |
{}
|
Returns:
| Type | Description |
|---|---|
EncoderBundle
|
The native model, tokenizer, provenance spec, and supported wrappers. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the encoder is unknown. |
TypeError
|
If loader options are unsupported for the selected family. |
BackboneCompatibilityError
|
If a custom builder returns the wrong spec. |
Source code in common/backbones/factory.py
build_backbone
¶
build_backbone(
name: str,
weights_path: Optional[str] = None,
device: str = "cuda",
) -> Tuple[Module, Callable, BackboneInfo]
Load the legacy (model, tokenizer, info) tuple.
New framework integrations should call :func:build_encoder; this wrapper
exists for vendored implementations that still consume native objects.