cofai.latent_codecs
BypassLatentCodec
BypassLatentCodec(**kwargs)
Pass-through codec used as the no-compression anchor.
The reconstructed features equal the input features and the reported bitstream is
empty, so the measured rate is zero. Plug it into DinoFeatureCodecModel to
benchmark task quality on uncompressed backbone features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
dict
|
Additional keyword arguments (currently unused). |
{}
|
FeatureScaleHyperprior
FeatureScaleHyperprior(N, M, **kwargs)
Scale Hyperprior model from J. Balle, D. Minnen, S. Singh, S.J. Hwang,
N. Johnston: "Variational Image Compression with a Scale Hyperprior"
<https://arxiv.org/abs/1802.01436>_ Int. Conf. on Learning Representations
(ICLR), 2018.
┌───┐ y ┌───┐ z ┌───┐ z_hat z_hat ┌───┐
x ──►─┤g_a├──►─┬──►──┤h_a├──►──┤ Q ├───►───·⋯⋯·───►───┤h_s├─┐
└───┘ │ └───┘ └───┘ EB └───┘ │
▼ │
┌─┴─┐ │
│ Q │ ▼
└─┬─┘ │
│ │
y_hat ▼ │
│ │
· │
GC : ◄─────────────────────◄────────────────────┘
· scales_hat
│
y_hat ▼
│
┌───┐ │
x_hat ──◄─┤g_s├────┘
└───┘
EB = Entropy bottleneck
GC = Gaussian conditional
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N
|
int
|
Number of channels |
required |
M
|
int
|
Number of channels in the expansion layers (last layer of the encoder and last layer of the hyperprior decoder) |
required |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N
|
int
|
Number of channels in the main network. |
required |
M
|
int
|
Number of channels in the expansion layers (last layer of the encoder and last layer of the hyperprior decoder). |
required |
**kwargs
|
dict
|
Additional keyword arguments passed to parent class. |
{}
|
downsampling_factor
property
downsampling_factor: int
Compute the downsampling factor of the model.
Returns:
| Name | Type | Description |
|---|---|---|
factor |
int
|
Downsampling factor (64 for this architecture). |
compress
compress(x)
Compress input tensor to bitstrings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor to compress. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
decompress
decompress(strings, shape)
Decompress bitstrings to reconstructed tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
list
|
List of compressed bitstrings [y_strings, z_strings]. Must contain exactly 2 elements. |
required |
shape
|
tuple
|
Spatial shape of the hyper latents (H, W). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
forward
forward(x)
Forward pass through the Scale Hyperprior model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor to compress. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
from_state_dict
classmethod
from_state_dict(state_dict)
Create a new model instance from state dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict
|
State dictionary containing model weights. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
model |
FeatureScaleHyperprior
|
New model instance with loaded weights. |
FixedGaussianCodec
FixedGaussianCodec(fixed_scale=1.0, device='cuda')
A simple "model-free" compressor for continuous features.
This codec does not inherit nn.Module and has no trainable parameters. It assumes all input features follow a fixed N(0, scale^2) distribution and uses CompressAI's GaussianConditional as an entropy coding utility.
compress
compress(features)
[Inference] Entropy-code features.
decompress
decompress(strings, shape)
[Inference] Decode features.
get_feat_and_rate_loss
get_feat_and_rate_loss(features)
[Training] Differentiable proxy of rate loss (bits/element).
inference
inference(features)
[Inference] Full compress+decompress flow with actual stream size.
HyperLatentCodecWithCtx
HyperLatentCodecWithCtx(entropy_bottleneck: EntropyBottleneck, h_a: Module, h_s: Module, quantizer: str = 'noise', **kwargs)
Entropy bottleneck codec with surrounding h_a and h_s transforms.
"Hyper" side-information branch introduced in
"Variational Image Compression with a Scale Hyperprior"
<https://arxiv.org/abs/1802.01436>_,
by J. Balle, D. Minnen, S. Singh, S.J. Hwang, and N. Johnston,
International Conference on Learning Representations (ICLR), 2018.
HyperLatentCodec should be used inside
HyperpriorLatentCodec to construct a full hyperprior.
┌───┐ z ┌───┐ z_hat z_hat ┌───┐
y ──►──┤h_a├──►──┤ Q ├───►───····───►───┤h_s├──►── params
└───┘ └───┘ EB └───┘
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entropy_bottleneck
|
EntropyBottleneck
|
Entropy bottleneck module for compressing hyper latents. |
required |
h_a
|
Module
|
Analysis transform that maps input to hyper latents. |
required |
h_s
|
Module
|
Synthesis transform that maps hyper latents to parameters. |
required |
quantizer
|
str
|
Quantization method. Options: "noise" (default) or "ste". Defaults to "noise". |
'noise'
|
**kwargs
|
dict
|
Additional keyword arguments passed to parent class. |
{}
|
compress
compress(y: Tensor, ctx: Tensor) -> Dict[str, Any]
Compress main latents to bitstrings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Tensor
|
Main latents to compress. |
required |
ctx
|
Tensor
|
Context tensor for conditional processing. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
decompress
decompress(strings: List[List[bytes]], shape: Tuple[int, int], ctx: Tensor, **kwargs) -> Dict[str, Any]
Decompress bitstrings to parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
list[list[bytes]]
|
List containing compressed bitstrings [z_strings]. |
required |
shape
|
tuple[int, int]
|
Spatial shape of hyper latents (H, W). |
required |
ctx
|
Tensor
|
Context tensor for conditional processing. |
required |
**kwargs
|
dict
|
Additional keyword arguments (unused). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
forward
forward(y: Tensor, ctx: Tensor) -> Dict[str, Any]
Forward pass through the hyper latent codec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Tensor
|
Main latents to process. |
required |
ctx
|
Tensor
|
Context tensor for conditional processing. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
HyperpriorLatentCodecWithCtx
HyperpriorLatentCodecWithCtx(latent_codec: Mapping[str, LatentCodec], **kwargs)
Hyperprior codec constructed from latent codec for y that
compresses y using params from hyper branch.
Hyperprior entropy modeling introduced in
"Variational Image Compression with a Scale Hyperprior"
<https://arxiv.org/abs/1802.01436>_,
by J. Balle, D. Minnen, S. Singh, S.J. Hwang, and N. Johnston,
International Conference on Learning Representations (ICLR), 2018.
┌──────────┐
┌─►──┤ lc_hyper ├──►─┐
│ └──────────┘ │
│ ▼ params
│ │
│ ┌──┴───┐
y ──┴───────►─────────┤ lc_y ├───►── y_hat
└──────┘
By default, the following codec is constructed:
┌───┐ z ┌───┐ z_hat z_hat ┌───┐
┌─►──┤h_a├──►──┤ Q ├───►───····───►───┤h_s├──►─┐
│ └───┘ └───┘ EB └───┘ │
│ │
│ ┌──────────────◄────────────┘
│ │ params
│ ┌──┴──┐
│ │ EP │
│ └──┬──┘
│ │
│ ┌───┐ y_hat ▼
y ──┴─►─┤ Q ├────►────····────►── y_hat
└───┘ GC
Common configurations of latent codecs include:
- entropy bottleneck
hyper(default) and gaussian conditionaly(default) - entropy bottleneck
hyper(default) and autoregressivey
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latent_codec
|
Mapping[str, LatentCodec]
|
Dictionary of latent codecs containing at least "y" and "hyper" keys: - "y": Codec for main latents. - "hyper": Codec for hyper latents (side information). |
required |
**kwargs
|
dict
|
Additional keyword arguments passed to parent class. |
{}
|
__getitem__
__getitem__(key: str) -> LatentCodec
Get a latent codec by key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Key to access latent codec (e.g., "y" or "hyper"). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
codec |
LatentCodec
|
Requested latent codec. |
compress
compress(y: Tensor, ctx: Tensor) -> Dict[str, Any]
Compress main latents to bitstrings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Tensor
|
Main latents to compress. |
required |
ctx
|
Tensor
|
Context tensor for conditional processing. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
decompress
decompress(strings: List[List[bytes]], shape: Dict[str, Tuple[int, ...]], ctx: Tensor, **kwargs) -> Dict[str, Any]
Decompress bitstrings to reconstructed main latents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
list[list[bytes]]
|
List of compressed bitstrings, with y_strings followed by z_strings. All y_strings must have the same length as z_strings. |
required |
shape
|
dict[str, tuple[int, ...]]
|
Dictionary with keys "y" and "hyper" containing spatial shapes for main and hyper latents respectively. |
required |
ctx
|
Tensor
|
Context tensor for conditional processing. |
required |
**kwargs
|
dict
|
Additional keyword arguments (unused). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
forward
forward(y: Tensor, ctx: Tensor) -> Dict[str, Any]
Forward pass through the hyperprior codec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Tensor
|
Main latents to process. |
required |
ctx
|
Tensor
|
Context tensor for conditional processing. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
MLoREFeatureCodec
MLoREFeatureCodec(feat_dim=768, N=1024, M=512)
Feature compression codec using hyperprior architecture.
This codec compresses ViT intermediate features using a learned transform coding approach with Gaussian conditional entropy model.
Architecture
- g_a: Analysis transform (encoder)
- g_s: Synthesis transform (decoder)
- h_a: Hyper analysis (side info encoder)
- h_s: Hyper synthesis (mean/scale prediction)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feat_dim
|
Input feature dimension (e.g., 768 for ViT-B) |
768
|
|
N
|
Number of channels in transforms |
1024
|
|
M
|
Bottleneck dimension |
512
|
compress
compress(x)
Compress features to bitstream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input feature tensor (B, C, H, W) |
required |
Returns:
| Type | Description |
|---|---|
|
dict following CoFAI coded_unit format: - strings: Dict of compressed bitstreams - shape: Tensor shape for decompression |
decompress
decompress(strings, shape, pstate=None)
Decompress bitstream to features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
Dict of compressed bitstreams |
required | |
shape
|
Hyper latent shape |
required | |
pstate
|
Additional state (y_shape, input_shape) |
None
|
Returns:
| Type | Description |
|---|---|
|
dict with keys: - x_hat: Reconstructed features |
forward
forward(x, target=None)
Forward pass for training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input feature tensor (B, C, H, W) |
required | |
target
|
Optional target for MSE loss (default: use x) |
None
|
Returns:
| Type | Description |
|---|---|
|
dict with keys: - bpp_loss: Bits per pixel loss - mse_loss: Reconstruction MSE loss - x_hat: Reconstructed features - likelihoods: Dict of likelihood tensors |
update
update(scale_table=None, force=False)
Update entropy model parameters.
MLoREFeatureCodecLight
MLoREFeatureCodecLight(feat_dim=768, N=512, M=256)
Lightweight feature compression codec.
Uses simpler transforms with fewer parameters for faster encoding/decoding, suitable for real-time applications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feat_dim
|
Input feature dimension |
768
|
|
N
|
Number of channels in transforms |
512
|
|
M
|
Bottleneck dimension |
256
|
compress
compress(x)
Compress features to bitstream.
decompress
decompress(strings, shape, pstate=None)
Decompress bitstream to features.
forward
forward(x, target=None)
Forward pass for training.
update
update(scale_table=None, force=False)
Update entropy model parameters.
OrthoRotationFeatureCodec
OrthoRotationFeatureCodec(orfc_weights_path: str, K: int | None = None, embedding_dim: int | None = None, norm_mode: str | None = None, n_prefix: int | None = None)
Fixed ORFC/Soft-PQ artifact exposed through the LatentCodec API.
K and embedding_dim are optional artifact assertions retained by
existing ORFC plans. New plans only need orfc_weights_path.
RawDtypeCodec
RawDtypeCodec(dtype: str = 'float16')
Cast features to a floating dtype and transmit their raw bytes.
This is a scalar quantization baseline, not an entropy codec. Decoded values are cast back to the encoder input dtype for downstream inference.
VQFeatureCodec
VQFeatureCodec(num_prefix_tokens: int = 0, drop_prefix: bool = False, **vqfc_cfg)
Adapt :class:~cofai.entropy_models.vqfc_model.VQFC to the latent-codec API.
DinoFeatureCodecModel / DinoSlideFeatureCodecModel expect a codec that
exposes forward(h, token_res, qp) -> {"h_hat", ...},
compress(h, token_res, qp) -> {"strings", "pstate"} and
decompress(strings, pstate) -> {"h_hat"} operating on encoder token tensors
of shape (B, N, C). The raw VQFC model instead works on patch-token
tensors and returns (quantized, mse, strings, inds).
This thin wrapper bridges the two. The number of prefix (cls / register)
tokens is declared explicitly via num_prefix_tokens instead of being
inferred from token_res.
When drop_prefix=True the leading num_prefix_tokens tokens are split
off and excluded from compression; VQFC runs on the patch tokens only and the
prefix is re-attached so the result can flow back through
backbone.decode_seg. Because segmentation decoding drops prefix tokens,
the reconstructed prefix values are irrelevant; the forward path keeps the
original prefix tokens while decompress (which has no access to them) uses
zeros, matching Dinov2OrigSlideSegVQFC.
When drop_prefix=False (default) the whole token sequence (prefix
included) is compressed and reconstructed, so the cls token survives the
round-trip. This is required for classification (backbone.decode_cls) and
matches the rate of the legacy Dinov2OrigClsVQFC (which compresses the
full h_dino).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_prefix_tokens
|
int
|
Number of leading prefix tokens (cls + register).
Only used when |
0
|
drop_prefix
|
bool
|
If |
False
|
**vqfc_cfg
|
Keyword arguments forwarded to :class: |
{}
|
VbrVitSeparateLatentCodec
VbrVitSeparateLatentCodec(h_dim=384, y_dim=256, z_dim=192, groups=16, num_prefix_tokens=1, **kwargs)
Vit latent codec with separate cls/patch modeling and variable bit-rate control.
This variant extends VitSeparateLatentCodec by introducing learnable
per-QP scaling factors on patch latents y (pre/post entropy coding),
following the same VBR strategy used in VbrVitUnionLatentCodec.
VisualTokenCodec
VisualTokenCodec(h_dim=384, y_dim=256, z_dim=192, groups=16, num_prefix_tokens=1, **kwargs)
Latent codec for ViT token features (Visual Token Codec).
Splits the sequence into prefix tokens (class/registers, length
num_prefix_tokens) and patch tokens. Prefix tokens are compressed with a
dedicated hyperprior on a tight B×C×L×1 layout; patch tokens are reshaped to a
spatial map B×C×H×W and compressed through an analysis transform f_a, a
standard hyperprior on the latent y, and a channel-grouped entropy coder.
Each patch group combines channel-wise context, spatial context
(checkerboard-masked convolutions on the latent grid), and hyperprior side info so
entropy modeling respects 2D patch geometry instead of treating tokens as an
unstructured vector.
Optional QP-indexed learnable gains scale patch latents around entropy coding (and scale features before/after shallow ViT blocks) to sweep rate–distortion points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h_dim
|
int
|
Channel dimension of ViT features. |
384
|
y_dim
|
int
|
Channel dimension of primary latent representation |
256
|
z_dim
|
int
|
Channel dimension of hyperprior latent representation |
192
|
groups
|
int or list[int]
|
Channel groups for channel-wise context modeling. |
16
|
num_prefix_tokens
|
int
|
Number of prefix/register tokens in the ViT feature. |
1
|
**kwargs
|
dict
|
Extra keyword arguments for compatibility (unused). |
{}
|
compress
compress(h, token_res, qp=0, **kwargs)
Compress ViT features with separate class and patch codecs and quantization parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
ViT output tensor of shape |
required |
token_res
|
tuple[int, int]
|
Spatial token resolution |
required |
qp
|
int
|
Quantization parameter index in |
0
|
**kwargs
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with keys:
|
decompress
decompress(strings, pstate, **kwargs)
Decompress bitstreams back to ViT features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
dict
|
Bitstreams for |
required |
pstate
|
dict
|
Side information produced by :meth: |
required |
**kwargs
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with key:
|
forward
forward(h, token_res, qp=0, **kwargs)
Forward pass for separate class/patch token compression with quantization parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
ViT output tensor of shape |
required |
token_res
|
tuple[int, int]
|
Spatial token resolution |
required |
qp
|
int
|
Quantization parameter index in |
0
|
**kwargs
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with keys:
|
VitSeparateLatentCodec
VitSeparateLatentCodec(h_dim=384, y_dim=256, z_dim=192, groups=16, num_prefix_tokens=5, **kwargs)
Vit latent codec with separate modeling of class and patch tokens.
This codec encodes class (prefix) tokens and patch tokens with different hyperprior models. Class tokens are compressed using a dedicated hyperprior codec, while patch tokens are compressed with a hyperprior + SCCTX model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h_dim
|
int
|
Channel dimension of ViT features. |
384
|
y_dim
|
int
|
Channel dimension of primary latent representation |
256
|
z_dim
|
int
|
Channel dimension of hyperprior latent representation |
192
|
groups
|
int or list[int]
|
Channel groups for channel-wise context modeling. |
16
|
num_prefix_tokens
|
int
|
Number of prefix/register tokens in the ViT feature. |
5
|
**kwargs
|
Extra keyword arguments for compatibility (unused). |
{}
|
compress
compress(h, token_res, **kwargs)
Compress ViT features with separate class and patch codecs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
ViT output tensor of shape |
required |
token_res
|
tuple[int, int]
|
Spatial token resolution |
required |
**kwargs
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with keys:
|
decompress
decompress(strings, pstate, **kwargs)
Decompress bitstreams back to ViT features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
dict
|
Bitstreams for |
required |
pstate
|
dict
|
Side information produced by :meth: |
required |
**kwargs
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with key:
|
forward
forward(h, token_res, **kwargs)
Forward pass for separate class/patch token compression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
ViT output tensor of shape |
required |
token_res
|
tuple[int, int]
|
Spatial token resolution |
required |
**kwargs
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with keys:
|
VitUnionLatentCodec
VitUnionLatentCodec(h_dim=384, y_dim=256, z_dim=192, groups=16, num_prefix_tokens=1, **kwargs)
Vit-based latent codec with joint modeling of cls token and patch tokens.
This codec takes ViT features as input and compresses the 2D patch tokens using a hyperprior + space-channel context model (SCCTX) as in [He2022]. It reconstructs the ViT feature map and re-injects learned register tokens before passing through transformer blocks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h_dim
|
int
|
Channel dimension of ViT features. |
384
|
y_dim
|
int
|
Channel dimension of primary latent representation |
256
|
z_dim
|
int
|
Channel dimension of hyperprior latent representation |
192
|
groups
|
int or list[int]
|
Channel groups for channel-wise context modeling.
If int, the channels are evenly split; if list, must sum to |
16
|
num_prefix_tokens
|
int
|
Number of prefix/register tokens in the ViT feature. |
1
|
**kwargs
|
dict
|
Extra keyword arguments for compatibility (unused). |
{}
|
compress
compress(h, token_res, **kwargs)
Compress ViT features into entropy-coded bitstreams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
ViT output tensor of shape |
required |
token_res
|
tuple[int, int]
|
Spatial token resolution |
required |
**kwargs
|
dict
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
dict
|
A dictionary with keys:
|
decompress
decompress(strings, pstate, **kwargs)
Decompress entropy-coded bitstreams back to ViT features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
dict
|
Bitstreams produced by :meth: |
required |
pstate
|
dict
|
Side information produced by :meth: |
required |
**kwargs
|
dict
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
dict
|
A dictionary with key:
|
forward
forward(h, token_res, **kwargs)
Forward pass for end-to-end rate–distortion training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
ViT output tensor of shape |
required |
token_res
|
tuple[int, int]
|
Spatial token resolution |
required |
**kwargs
|
dict
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
dict
|
A dictionary with keys:
|
VitUnionLatentCodecWithCtx
VitUnionLatentCodecWithCtx(h_dim=384, y_dim=256, z_dim=192, ctx_dim=256, groups=16, **kwargs)
Vit union latent codec conditioned on an external context feature map.
This codec jointly compresses ViT patch tokens and an additional context feature map. The context is injected into both the analysis and synthesis transforms as well as the hyperprior pathway.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h_dim
|
int
|
Channel dimension of ViT features. |
384
|
y_dim
|
int
|
Channel dimension of primary latent representation |
256
|
z_dim
|
int
|
Channel dimension of hyperprior latent representation |
192
|
ctx_dim
|
int
|
Channel dimension of the external context feature map. |
256
|
groups
|
int or list[int]
|
Channel groups for channel-wise context modeling. |
16
|
**kwargs
|
dict
|
Extra keyword arguments for compatibility (unused). |
{}
|
compress
compress(h, ctx, token_res)
Compress ViT features conditioned on a context feature map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
ViT output tensor of shape |
required |
ctx
|
Tensor
|
Context feature map of shape |
required |
token_res
|
tuple[int, int]
|
Spatial token resolution |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
dict
|
A dictionary with keys:
|
decompress
decompress(strings, pstate, ctx, **kwargs)
Decompress context-conditioned bitstreams back to ViT features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
dict
|
Bitstreams with keys |
required |
pstate
|
dict
|
Side information produced by :meth: |
required |
ctx
|
Tensor
|
Context feature map used also at decoding time. |
required |
**kwargs
|
dict
|
Unused keyword arguments for API compatibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
dict
|
A dictionary with keys:
|
forward
forward(h, ctx, token_res)
Forward pass with context-conditioned hyperprior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
ViT output tensor of shape |
required |
ctx
|
Tensor
|
Context feature map of shape |
required |
token_res
|
tuple[int, int]
|
Spatial token resolution |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
dict
|
A dictionary with keys:
|
VtmCodec
VtmCodec(repo_dir)
VTM (VVC Test Model) codec wrapper for video encoding and decoding.
This class provides an interface to VTM encoder and decoder executables for compressing and decompressing video data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_dir
|
str
|
Path to VTM repository directory containing bin/ and cfg/ folders. |
required |
compress
compress(raw_path, bin_path, width, height, qp: int, bitdepth: int = 8, chroma_format: str = '400')
Compress raw video file using VTM encoder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_path
|
str
|
Path to input raw YUV file. |
required |
bin_path
|
str
|
Path to output compressed bitstream file. |
required |
width
|
int
|
Video width in pixels. |
required |
height
|
int
|
Video height in pixels. |
required |
qp
|
int
|
Quantization parameter (0-51, lower is higher quality). |
required |
bitdepth
|
int
|
Bit depth (8 or 10). Defaults to 8. |
8
|
chroma_format
|
str
|
Chroma format. Defaults to "400" (grayscale). |
'400'
|
decompress
decompress(bin_path, rec_path, bit_depth=8)
VtmFeatureCodec
VtmFeatureCodec(cfg)
VTM-based feature codec for compressing neural network features.
This codec applies truncation, quantization, packing, VTM encoding/decoding, and post-processing to compress features from various model types (llama3, dinov2, sd3).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
dict
|
Configuration object containing:
|
required |
compress
compress(org_feat, qp: int)
Compress features using VTM codec.
Expected feature shape: (N_crop, N_layer, H*W+1, C)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
org_feat
|
ndarray
|
Original features to compress. |
required |
qp
|
int
|
Quantization parameter for VTM encoding. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
output |
dict
|
Dictionary containing:
|
decompress
decompress(strings, pstate, **kwargs)
Decompress features from VTM bitstream.
Note: model_type, bit_depth, trun_low, trun_high are fixed in self.cfg.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strings
|
dict
|
Dictionary with key "vtm" containing compressed bitstring. |
required |
pstate
|
dict
|
State dictionary containing:
|
required |
**kwargs
|
dict
|
Additional keyword arguments (unused). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
decoded |
dict
|
Dictionary containing: - "h_hat" (numpy.ndarray): Decoded features with original shape. |
forward_test
forward_test(org_feat, qp: int)
Forward test method for debugging (includes timing measurements).
This method performs full encode-decode cycle and returns both compressed representation and decoded features with timing information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
org_feat
|
ndarray
|
Original features to compress. |
required |
qp
|
int
|
Quantization parameter for VTM encoding. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
coded_unit |
dict
|
Dictionary containing:
|
decoded |
dict
|
Dictionary containing:
|
VtmLatentCodec
VtmLatentCodec(cfg, **kwargs)
Adapt :class:VtmFeatureCodec to the latent-codec API.
DinoFeatureCodecModel / DinoSlideFeatureCodecModel expect a codec that
exposes forward(h, token_res, qp) -> {"h_hat", "strings", ...},
compress(h, token_res, qp) -> {"strings", "pstate"} and
decompress(strings, pstate) -> {"h_hat"} operating on encoder token
tensors of shape (B, N, C). The raw :class:VtmFeatureCodec instead works
on numpy arrays packed as (B, 1, N, C) (its model_type="dinov2"
packing) and keeps the VVC bitstream on disk between compress and
decompress.
This thin wrapper bridges the two: tokens (B, N, C) are reshaped to the
(B, 1, N, C) array VTM expects, run through truncation + uniform
quantization + VTM intra coding, and the dequantized result is returned as a
torch tensor on the codec's device. Unlike VQFC, VTM compresses all tokens
(cls / register prefix included), matching Dinov2TimmVTM /
Dinov2TimmSlideVtm; token_res is accepted for API symmetry but unused.
When used by :class:DinoSlideFeatureCodecModel with
slide_codec_mode="stacked", the model stacks every crop into the batch
dimension so VTM packs all crops into a single image and encodes them with one
VTM call -- reproducing the original sliding-window VTM rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
dict | DictConfig
|
Configuration forwarded to
:class: |
required |