Tokenization
tokenization
Tokenization and compression for DHB invariants (VLA).
Modules: - vqvae: Basic VQ-VAE tokenizer (DHBTokenizer) - rvq: Residual VQ for higher capacity (ResidualVQTokenizer) - hierarchical: Multi-level hierarchical tokenization - compression: BPE, entropy coding, RLE for token sequences - fast_tokenizer: FAST-style DCT + BPE tokenizer (no PyTorch needed) - fsq: Finite Scalar Quantization (no learned codebook) - register_encoder: Transformer encoder with register tokens - nested_dropout: Masked nested dropout for ordered token spaces - oat_decoder: Cross-attention decoder with prefix support - oat_tokenizer: Combined OAT-style tokenizer
Classes
BPECompressor
Byte-Pair Encoding for token sequences.
Merges frequent token pairs into super-tokens, reducing sequence length while preserving exact recoverability (lossless).
Inspired by FAST (Physical Intelligence, 2025) which achieves ~10x compression on action sequences via DCT + BPE.
Example
compressor = BPECompressor(vocab_size=512, num_merges=100) compressor.fit(token_corpus) # List of token sequences compressed = compressor.encode([1, 2, 1, 2, 3]) # [256, 256, 3] if (1,2)->256 original = compressor.decode(compressed)
Source code in src/dhb_xr/tokenization/compression.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | |
Attributes
Functions
__init__
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocab_size
|
int
|
Original VQ codebook size (tokens 0 to vocab_size-1) |
256
|
num_merges
|
int
|
Number of BPE merges to learn |
100
|
Source code in src/dhb_xr/tokenization/compression.py
compression_ratio
Compute compression ratio (original_len / compressed_len).
Source code in src/dhb_xr/tokenization/compression.py
decode
Decode a compressed sequence back to original tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Union[List[int], ndarray]
|
Compressed token sequence |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
Original token sequence |
Source code in src/dhb_xr/tokenization/compression.py
encode
Encode a token sequence using learned BPE merges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Union[List[int], ndarray]
|
Original token sequence |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
Compressed token sequence |
Source code in src/dhb_xr/tokenization/compression.py
fit
Learn BPE merges from a corpus of token sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_sequences
|
List[List[int]]
|
List of token sequences (each a list of ints) |
required |
Returns:
| Type | Description |
|---|---|
BPECompressor
|
self |
Source code in src/dhb_xr/tokenization/compression.py
get_stats
Get compression statistics.
CausalConv1dEncoder
Bases: Module
Stack of causal convs: (B, T, C) -> (B, T, D).
Source code in src/dhb_xr/tokenization/causal_encoder.py
DHBTokenizer
Bases: Module
Causal VQ-VAE for invariant sequences. invariants (B, T, C) -> tokens (B, T), reconstructed (B, T, C).
Source code in src/dhb_xr/tokenization/vqvae.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
Functions
decode_from_latent
Decode from continuous latent to invariants.
Bypasses the VQ step, useful for flow matching generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Continuous latent (B, T, latent_dim). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed invariants (B, T, invariant_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
decode_tokens
Decode token indices to invariants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Tensor
|
Token indices (B, T). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed invariants (B, T, invariant_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
embed_tokens
Convert token indices to embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Tensor
|
Token indices (B, T). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Token embeddings (B, T, latent_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
encode_continuous
Encode invariants to continuous latent space (before quantization).
This is useful for flow matching which operates in continuous space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariants
|
Tensor
|
Input invariant sequences (B, T, C). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Continuous latent z (B, T, latent_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
get_codebook_embeddings
Get the VQ codebook embeddings.
Useful for flow matching in embedding space or visualization.
Returns:
| Type | Description |
|---|---|
Tensor
|
Codebook embeddings (codebook_size, latent_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
quantize
Quantize continuous latent to discrete tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Continuous latent (B, T, latent_dim). |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (indices, z_q_st, z_q). |
EntropyCompressor
Entropy coding (Huffman) for token sequences.
Assigns variable-length codes based on token frequencies, achieving near-optimal bits-per-token based on entropy.
For RVQ indices with K=256, naive encoding = 8 bits/token. With entropy coding: typically 4-6 bits/token (1.5-2x compression).
Source code in src/dhb_xr/tokenization/compression.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
Functions
bits_per_token
decode
Decode binary string back to tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_string
|
str
|
Encoded binary string |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
Original token sequence |
Source code in src/dhb_xr/tokenization/compression.py
encode
Encode tokens to binary string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Union[List[int], ndarray]
|
Token sequence |
required |
Returns:
| Type | Description |
|---|---|
str
|
Binary string (e.g., "0110101...") |
Source code in src/dhb_xr/tokenization/compression.py
fit
Build Huffman tree from token frequencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_sequences
|
List[List[int]]
|
List of token sequences |
required |
Returns:
| Type | Description |
|---|---|
EntropyCompressor
|
self |
Source code in src/dhb_xr/tokenization/compression.py
get_stats
Get compression statistics.
Source code in src/dhb_xr/tokenization/compression.py
theoretical_entropy
Compute theoretical entropy H = -sum(p * log2(p)).
Source code in src/dhb_xr/tokenization/compression.py
FASTTokenizer
FAST-style tokenizer: DCT frequency compression + BPE.
Converts continuous invariant (or action) chunks into a compact sequence of discrete tokens using the Discrete Cosine Transform for energy compaction and Byte-Pair Encoding for further compression.
Example
tokenizer = FASTTokenizer(scale=10.0, vocab_size=1024, num_merges=200)
Fit BPE on a corpus of invariant chunks
corpus = [np.random.randn(50, 8) for _ in range(100)] tokenizer.fit(corpus)
Tokenize a single chunk
tokens = tokenizer.encode(np.random.randn(50, 8)) recon = tokenizer.decode(tokens, time_horizon=50, dim=8)
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
Functions
__init__
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale
|
float
|
Scaling factor for DCT coefficients before rounding. Higher values preserve more detail but increase alphabet size. |
10.0
|
vocab_size
|
int
|
Maximum BPE vocabulary size (includes initial alphabet + merges). |
1024
|
num_merges
|
int
|
Number of BPE merge operations to learn. |
200
|
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
compression_ratio
Compute compression ratio for a chunk.
Returns:
| Type | Description |
|---|---|
float
|
original_values / compressed_tokens. |
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
decode
Decode tokens back to a continuous chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
List[int]
|
BPE-compressed token sequence. |
required |
time_horizon
|
Optional[int]
|
Number of timesteps T (uses cached value if None). |
None
|
dim
|
Optional[int]
|
Invariant/action dimension D (uses cached value if None). |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
(T, D) reconstructed chunk. |
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
decode_batch
Decode a batch of token sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_sequences
|
List[List[int]]
|
List of B token sequences. |
required |
time_horizon
|
Optional[int]
|
Number of timesteps T. |
None
|
dim
|
Optional[int]
|
Invariant/action dimension D. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
(B, T, D) batch of reconstructed chunks. |
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
encode
Tokenize a single invariant/action chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk
|
ndarray
|
(T, D) continuous chunk. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
List of BPE-compressed token IDs. |
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
encode_batch
Tokenize a batch of chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
ndarray
|
(B, T, D) batch of chunks. |
required |
Returns:
| Type | Description |
|---|---|
List[List[int]]
|
List of B token sequences. |
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
fit
Learn BPE merges from a corpus of invariant/action chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
List[ndarray]
|
List of (T_i, D) arrays. Chunks may have different lengths but must share the same dimension D. |
required |
Returns:
| Type | Description |
|---|---|
FASTTokenizer
|
self (fitted tokenizer). |
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
get_stats
Get tokenizer statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk
|
Optional[ndarray]
|
Optional chunk to compute per-chunk statistics. |
None
|
Returns:
| Type | Description |
|---|---|
Dict
|
Dictionary of statistics. |
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
reconstruction_error
Compute MSE reconstruction error for a chunk.
Source code in src/dhb_xr/tokenization/fast_tokenizer.py
FSQ
Bases: Module
Finite Scalar Quantization.
Maps continuous latents to discrete codes by bounding (tanh) and rounding. No learned codebook -- the codebook is implicitly defined by the levels.
Example
fsq = FSQ(levels=[8, 5, 5, 5])
Effective codebook size: 8 * 5 * 5 * 5 = 1000
z = torch.randn(2, 10, 4) # (B, T, D) where D = len(levels) z_q, indices = fsq(z)
z_q: (2, 10, 4) quantized, indices: (2, 10) codebook indices
z_recon = fsq.indices_to_embedding(indices) assert torch.allclose(z_q, z_recon)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
levels
|
List[int]
|
List of quantization levels per dimension. E.g., [8, 5, 5, 5] -> codebook size 1000. |
required |
drop_quant_p
|
float
|
During training, probability of skipping quantization per sample (quantization dropout for regularization). |
0.0
|
Source code in src/dhb_xr/tokenization/fsq.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | |
Attributes
Functions
bound
Bound z to the valid range for each level via tanh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
(..., D) unbounded latent vectors. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
(..., D) bounded latent vectors in [-half_l, half_l]. |
Source code in src/dhb_xr/tokenization/fsq.py
codes_to_indices
Convert quantized codes to flat codebook indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zhat
|
Tensor
|
(..., D) quantized codes (normalized). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
(...) integer indices. |
Source code in src/dhb_xr/tokenization/fsq.py
forward
Quantize and return codes + indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
(..., D) continuous latent vectors. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Tuple of: |
Tensor
|
|
Tuple[Tensor, Tensor]
|
|
Source code in src/dhb_xr/tokenization/fsq.py
indices_to_embedding
Convert flat codebook indices to normalized code vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Tensor
|
(...) integer indices. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
(..., D) normalized code vectors. |
Source code in src/dhb_xr/tokenization/fsq.py
quantize
Quantize z: bound, round (STE), normalize to [-1, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
(..., D) unbounded latent vectors. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
(..., D) quantized and normalized vectors. |
Source code in src/dhb_xr/tokenization/fsq.py
HierarchicalTokenizer
Bases: Module
Hierarchical RVQ with variable-rate output.
Provides coarse-to-fine tokenization: - Level 0: Low-frequency global structure (high compression) - Level 1-N: Residual details (configurable refinement)
For inference, can truncate to fewer levels for faster/coarser output.
Example
tokenizer = HierarchicalTokenizer( ... invariant_dim=8, latent_dim=32, codebook_size=256, num_levels=4 ... ) tokens, recon = tokenizer(invariants)
Coarse only (4x fewer tokens)
tokens_coarse, recon_coarse = tokenizer(invariants, max_level=1)
Source code in src/dhb_xr/tokenization/hierarchical.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
Functions
__init__
__init__(
invariant_dim, latent_dim, codebook_size, num_levels=4, temporal_downsample=2, num_layers=2
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariant_dim
|
int
|
DHB invariant dimension (typically 8) |
required |
latent_dim
|
int
|
Latent embedding dimension |
required |
codebook_size
|
int
|
VQ codebook size per level |
required |
num_levels
|
int
|
Number of hierarchy levels |
4
|
temporal_downsample
|
int
|
Downsample factor between levels |
2
|
num_layers
|
int
|
Conv layers per encoder/decoder |
2
|
Source code in src/dhb_xr/tokenization/hierarchical.py
forward
Hierarchical encoding and decoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariants
|
Tensor
|
(B, T, invariant_dim) input |
required |
max_level
|
int
|
Stop at this level (None = all levels) |
None
|
return_all_levels
|
bool
|
Return tokens/recon at each level |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
all_tokens |
tuple
|
List of (B, T_l) tokens per level |
reconstructed |
tuple
|
(B, T, invariant_dim) reconstruction |
level_info |
tuple
|
Optional dict with per-level details |
Source code in src/dhb_xr/tokenization/hierarchical.py
get_compression_stats
Compute compression statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
T
|
int
|
Original sequence length |
required |
max_level
|
int
|
Number of levels to use |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Compression statistics |
Source code in src/dhb_xr/tokenization/hierarchical.py
loss
Compute hierarchical loss with per-level weighting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariants
|
Tensor
|
Original input |
required |
reconstructed
|
Tensor
|
Reconstruction |
required |
all_z
|
list
|
Latents at each level |
required |
all_z_q
|
list
|
Quantized latents at each level |
required |
beta
|
float
|
Commitment loss weight |
0.25
|
level_weights
|
list
|
Optional weights per level (default: exponential decay) |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Total loss |
Source code in src/dhb_xr/tokenization/hierarchical.py
MaskedNestedDropout
Bases: Module
Nested dropout module that replaces trailing tokens with a learnable mask token during training.
During training
Randomly sample keep_k in [1, N], replace tokens beyond keep_k with a learnable mask token.
During evaluation
If eval_keep_k is provided, mask tokens beyond keep_k. Otherwise, pass through without masking (use all tokens).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
int
|
Embedding dimension of the mask token. |
required |
mode
|
str
|
Sampling strategy for keep_k during training. - "disable": No dropout (pass-through). - "uniform": Uniform probability across all prefix lengths. - "pow2": Only sample power-of-2 prefix lengths. - "linear_biased": Linear bias toward longer prefixes. - "quadratic_biased": Quadratic bias toward longer prefixes. - "cubic_biased": Cubic bias toward longer prefixes. |
'uniform'
|
Example
dropout = MaskedNestedDropout(dim=64, mode="uniform") x = torch.randn(2, 8, 64) # (B, K, D)
Training: some trailing tokens replaced with mask
dropout.train() y = dropout(x)
Eval with prefix: decode with first 4 tokens only
dropout.eval() y = dropout(x, eval_keep_k=[4, 4])
Source code in src/dhb_xr/tokenization/nested_dropout.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
Functions
forward
Apply nested dropout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
(B, N, D) token sequence. |
required |
eval_keep_k
|
Optional[List[int]]
|
Optional list of B integers specifying how many tokens to keep per sample during evaluation. If None during eval, all tokens are kept. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
(B, N, D) token sequence with trailing tokens masked. |
Source code in src/dhb_xr/tokenization/nested_dropout.py
OATDecoder
Bases: Module
Cross-attention decoder for register-token latents.
Decodes (B, K, latent_dim) register latents -> (B, T, output_dim).
Architecture: - Learned positional queries of length T (output timesteps) - nn.TransformerDecoder with cross-attention to register latents - Linear head to project to output dimension
Works with MaskedNestedDropout: during training/eval, some trailing register tokens may be replaced with a mask token, enabling variable-quality prefix decoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dim
|
int
|
Dimension of output features (e.g., 8 for DHB invariants). |
required |
output_horizon
|
int
|
Number of output timesteps T. |
required |
emb_dim
|
int
|
Internal transformer embedding dimension. |
64
|
latent_dim
|
int
|
Dimension of input register latents. |
16
|
latent_horizon
|
int
|
Number of register tokens K. |
8
|
depth
|
int
|
Number of transformer decoder layers. |
4
|
num_heads
|
int
|
Number of attention heads. |
4
|
dropout
|
float
|
Dropout rate. |
0.1
|
use_causal_decoder
|
bool
|
If True, apply causal mask to output queries (for autoregressive generation). |
False
|
Example
dec = OATDecoder(output_dim=8, output_horizon=50, emb_dim=64, ... latent_dim=16, latent_horizon=8, depth=4) latents = torch.randn(2, 8, 16) recon = dec(latents) # (2, 50, 8)
Prefix decoding: only use first 4 register tokens
recon_coarse = dec(latents, eval_keep_k=[4, 4])
Source code in src/dhb_xr/tokenization/oat_decoder.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | |
Functions
forward
Decode register latents to output sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latents
|
Tensor
|
(B, K, latent_dim) register token latents. May have trailing tokens masked by MaskedNestedDropout. |
required |
eval_keep_k
|
Optional[List[int]]
|
Optional list of B integers. If provided, only the first keep_k latent tokens per sample are considered "real" (rest are masked). This is handled upstream by MaskedNestedDropout; this parameter is kept for API consistency. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
(B, T, output_dim) reconstructed output sequence. |
Source code in src/dhb_xr/tokenization/oat_decoder.py
OATTokenizer
Bases: Module
OAT-style tokenizer with register encoding, FSQ, nested dropout, and cross-attention decoding.
Produces an ordered sequence of K discrete tokens from T input timesteps. Any prefix of k <= K tokens can be decoded to a valid reconstruction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dim
|
int
|
Dimension of input features (e.g., 8 for DHB invariants). |
8
|
input_horizon
|
int
|
Number of input timesteps T. |
50
|
emb_dim
|
int
|
Internal transformer embedding dimension. |
64
|
latent_dim
|
int
|
FSQ latent dimension (= number of FSQ levels). |
4
|
num_registers
|
int
|
Number of register tokens K (compression factor). |
8
|
fsq_levels
|
Optional[List[int]]
|
List of FSQ quantization levels per dimension. |
None
|
encoder_depth
|
int
|
Number of transformer encoder layers. |
4
|
decoder_depth
|
int
|
Number of transformer decoder layers. |
4
|
num_heads
|
int
|
Number of attention heads. |
4
|
dropout
|
float
|
Dropout rate. |
0.1
|
nested_dropout_mode
|
str
|
Sampling mode for nested dropout. |
'uniform'
|
drop_quant_p
|
float
|
FSQ quantization dropout probability. |
0.0
|
use_causal_decoder
|
bool
|
Use causal mask in decoder queries. |
False
|
Example
tok = OATTokenizer( ... input_dim=8, input_horizon=50, emb_dim=64, latent_dim=4, ... num_registers=8, fsq_levels=[8, 5, 5, 5], ... encoder_depth=4, decoder_depth=4 ... ) x = torch.randn(2, 50, 8) loss = tok(x) print(f"Training loss: {loss.item():.4f}")
Tokenize
tokens = tok.tokenize(x) # (2, 8)
Detokenize with prefix
recon = tok.detokenize(tokens[:, :4]) # use first 4 tokens
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | |
Attributes
Functions
autoencode
Full encode-decode roundtrip.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
(B, T, input_dim) input sequence. |
required |
eval_keep_k
|
Optional[List[int]]
|
Optional prefix lengths for anytime decoding. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
(B, T, input_dim) reconstructed sequence. |
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
decode
Decode quantized latents (with optional prefix masking).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latents
|
Tensor
|
(B, K, latent_dim) quantized register latents. |
required |
eval_keep_k
|
Optional[List[int]]
|
Optional list of B integers for prefix decoding. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
(B, T, input_dim) reconstructed sequence. |
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
detokenize
Convert token indices back to reconstructed sequence.
Supports prefix decoding: pass a subset of tokens (first k columns) to get a coarser reconstruction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
(B, K) or (B, k) token indices where k <= K. |
required |
eval_keep_k
|
Optional[List[int]]
|
Optional list specifying keep_k per sample. If tokens has fewer columns than num_registers, keep_k is inferred automatically. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
(B, T, input_dim) reconstructed sequence. |
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
encode
Encode input to quantized latents and token indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
(B, T, input_dim) input sequence. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Tuple of: |
Tensor
|
|
Tuple[Tensor, Tensor]
|
|
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
forward
Training forward pass: encode -> quantize -> dropout -> decode -> loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
(B, T, input_dim) input invariant/action sequence. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar MSE reconstruction loss. |
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
get_compression_stats
Get compression statistics.
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
get_optimizer
Create AdamW optimizer with proper weight decay groups.
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
tokenize
Convert input to discrete token indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
(B, T, input_dim) input sequence. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
(B, K) token indices. |
Source code in src/dhb_xr/tokenization/oat_tokenizer.py
ProgressiveTokenizer
Bases: Module
Progressive refinement tokenizer.
Outputs can be truncated at any level for variable-rate decoding: - 1 level: ~4x compression, coarse motion - 2 levels: ~2x compression, medium detail - 4 levels: ~1x compression, full fidelity
Ideal for streaming/bandwidth-adaptive applications.
Source code in src/dhb_xr/tokenization/hierarchical.py
Functions
forward
Progressive tokenization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariants
|
Tensor
|
(B, T, D) input |
required |
num_refine
|
int
|
Number of refinement levels (0 = base only) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
all_tokens |
tuple
|
List of token tensors |
reconstructed |
tuple
|
Final reconstruction |
Source code in src/dhb_xr/tokenization/hierarchical.py
RLECompressor
Run-Length Encoding for token sequences.
Compresses repeated tokens (common in static/low-motion segments). Uses a special "repeat" token followed by (token, count) pairs.
Example
[5, 5, 5, 5, 3, 3] -> [(REPEAT, 5, 4), (REPEAT, 3, 2)] or simplified: [RLE_MARKER, 5, 4, RLE_MARKER, 3, 2]
Source code in src/dhb_xr/tokenization/compression.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
Functions
__init__
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_run
|
int
|
Minimum run length to compress (shorter runs kept as-is) |
3
|
max_count
|
int
|
Maximum count per run (limits encoding overhead) |
255
|
Source code in src/dhb_xr/tokenization/compression.py
compression_ratio
Compute compression ratio.
Source code in src/dhb_xr/tokenization/compression.py
decode
Decode RLE-encoded sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoded
|
List[Tuple[int, int]]
|
List of (token, count) tuples |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
Original token sequence |
Source code in src/dhb_xr/tokenization/compression.py
encode
Encode tokens with run-length encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Union[List[int], ndarray]
|
Token sequence |
required |
Returns:
| Type | Description |
|---|---|
List[Tuple[int, int]]
|
List of (token, count) tuples |
Source code in src/dhb_xr/tokenization/compression.py
get_stats
Get RLE statistics for a sequence.
Source code in src/dhb_xr/tokenization/compression.py
RegisterEncoder
Bases: Module
Transformer encoder with register tokens.
Compresses (B, T, input_dim) -> (B, num_registers, latent_dim).
The key architectural innovation: learnable register tokens are appended to the embedded input, processed through a transformer with a causal-last attention mask, and then extracted as the compressed representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dim
|
int
|
Dimension of input features (e.g., 8 for DHB invariants). |
required |
emb_dim
|
int
|
Internal transformer embedding dimension. |
64
|
latent_dim
|
int
|
Output dimension per register token. |
16
|
num_registers
|
int
|
Number of register tokens (K). Controls compression. |
8
|
depth
|
int
|
Number of transformer encoder layers. |
4
|
num_heads
|
int
|
Number of attention heads. |
4
|
dropout
|
float
|
Dropout rate. |
0.1
|
max_seq_len
|
int
|
Maximum input sequence length. |
512
|
Example
enc = RegisterEncoder(input_dim=8, emb_dim=64, latent_dim=16, ... num_registers=8, depth=4) x = torch.randn(2, 50, 8) # (B, T=50, D=8) z = enc(x) # (B, 8, 16) -- 50 timesteps -> 8 tokens
Source code in src/dhb_xr/tokenization/register_encoder.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
Functions
forward
Encode input sequence to register token latents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
(B, T, input_dim) input invariant/action sequence. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
(B, num_registers, latent_dim) compressed representation. |
Source code in src/dhb_xr/tokenization/register_encoder.py
ResidualVQTokenizer
Bases: Module
RVQ: multiple codebooks on residual. invariants (B, T, C) -> list of (B, T) tokens, (B, T, C) reconstructed.
Source code in src/dhb_xr/tokenization/rvq.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
Functions
decode_from_latent
Decode from continuous latent to invariants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Continuous latent (B, T, latent_dim). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed invariants (B, T, invariant_dim). |
Source code in src/dhb_xr/tokenization/rvq.py
decode_tokens
Decode RVQ token indices to invariants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_indices
|
list
|
List of token indices, each (B, T). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed invariants (B, T, invariant_dim). |
Source code in src/dhb_xr/tokenization/rvq.py
embed_tokens
Convert RVQ token indices to summed embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_indices
|
list
|
List of token indices, each (B, T). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Summed embeddings (B, T, latent_dim). |
Source code in src/dhb_xr/tokenization/rvq.py
encode_continuous
Encode invariants to continuous latent space (before quantization).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariants
|
Tensor
|
Input invariant sequences (B, T, C). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Continuous latent z (B, T, latent_dim). |
Source code in src/dhb_xr/tokenization/rvq.py
encode_partial
Encode with partial RVQ (for hierarchical VFM).
Uses only the first num_codebooks codebooks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariants
|
Tensor
|
Input invariant sequences (B, T, C). |
required |
num_codebooks
|
int
|
Number of codebooks to use. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (all_indices, z_sum, reconstructed). |
Source code in src/dhb_xr/tokenization/rvq.py
get_all_codebook_embeddings
Get all codebook embeddings.
Returns:
| Type | Description |
|---|---|
list
|
List of codebook embeddings, each (codebook_size, latent_dim). |
get_codebook_embeddings
Get codebook embeddings for a specific codebook.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codebook_idx
|
int
|
Index of the codebook (0 to num_codebooks-1). |
0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Codebook embeddings (codebook_size, latent_dim). |
Source code in src/dhb_xr/tokenization/rvq.py
quantize
Quantize continuous latent using RVQ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Continuous latent (B, T, latent_dim). |
required |
num_codebooks
|
int
|
Number of codebooks to use (default: all). |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (all_indices, z_sum) where all_indices is list of (B, T). |
Source code in src/dhb_xr/tokenization/rvq.py
TokenCompressor
Unified compression pipeline for DHB-Token sequences.
Combines multiple compression methods for optimal results: 1. RLE for static segments (lossless, good for low-motion) 2. BPE for pattern merging (lossless, 2-4x on invariant patterns) 3. Entropy coding for final bitstream (lossless, 1.5-2x additional)
Overall achievable: 3-8x compression on typical DHB-Token sequences.
Example
compressor = TokenCompressor(vocab_size=256) compressor.fit(training_sequences)
Compress
compressed = compressor.compress(tokens) print(f"Ratio: {compressor.compression_ratio(tokens):.1f}x")
Decompress (lossless)
recovered = compressor.decompress(compressed) assert recovered == list(tokens)
Source code in src/dhb_xr/tokenization/compression.py
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 | |
Functions
__init__
__init__(
vocab_size=256, use_rle=True, use_bpe=True, use_entropy=True, bpe_merges=100, rle_min_run=3
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocab_size
|
int
|
VQ codebook size |
256
|
use_rle
|
bool
|
Enable run-length encoding |
True
|
use_bpe
|
bool
|
Enable byte-pair encoding |
True
|
use_entropy
|
bool
|
Enable entropy (Huffman) coding |
True
|
bpe_merges
|
int
|
Number of BPE merges to learn |
100
|
rle_min_run
|
int
|
Minimum run length for RLE |
3
|
Source code in src/dhb_xr/tokenization/compression.py
compress
Compress a token sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Union[List[int], ndarray]
|
Token sequence |
required |
Returns:
| Type | Description |
|---|---|
Dict
|
Dict with compressed data and metadata |
Source code in src/dhb_xr/tokenization/compression.py
compression_ratio
Compute overall compression ratio for a sequence.
decompress
Decompress back to original tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compressed
|
Dict
|
Output from compress() |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
Original token sequence |
Source code in src/dhb_xr/tokenization/compression.py
fit
Fit all compression stages on training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_sequences
|
List[List[int]]
|
List of token sequences |
required |
Returns:
| Type | Description |
|---|---|
TokenCompressor
|
self |
Source code in src/dhb_xr/tokenization/compression.py
get_stats
Get overall compression statistics.
Source code in src/dhb_xr/tokenization/compression.py
TokenReuser
Token reuse detector for inference acceleration.
Inspired by FlashVLA (2025): Skip decoding when tokens are stable/repeated, reusing previous outputs. Provides 2-5x effective speedup in long-horizon tasks.
Works by detecting: 1. Exact token repeats (static segments) 2. Token sequences matching known patterns (from database) 3. Low-variance token regions (approximate reuse)
Source code in src/dhb_xr/tokenization/compression.py
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 | |
Functions
__init__
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_size
|
int
|
Window for detecting stable regions |
5
|
similarity_threshold
|
float
|
Threshold for approximate matching |
0.9
|
Source code in src/dhb_xr/tokenization/compression.py
compute_reuse_potential
Analyze reuse potential for a sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Union[List[int], ndarray]
|
Token sequence |
required |
Returns:
| Type | Description |
|---|---|
Dict
|
Statistics on reuse potential |
Source code in src/dhb_xr/tokenization/compression.py
detect_stable_regions
Detect regions where tokens are stable (can reuse previous decoding).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Union[List[int], ndarray]
|
Token sequence |
required |
Returns:
| Type | Description |
|---|---|
List[Tuple[int, int, bool]]
|
List of (start, end, is_stable) tuples |
Source code in src/dhb_xr/tokenization/compression.py
Functions
compress_token_sequence
Compress a token sequence with specified method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Union[List[int], ndarray]
|
Token sequence |
required |
vocab_size
|
int
|
VQ codebook size |
256
|
method
|
str
|
"bpe", "entropy", "rle", or "full" |
'bpe'
|
**kwargs
|
Additional arguments for compressor |
{}
|
Returns:
| Type | Description |
|---|---|
Dict
|
Compression result dict |
Source code in src/dhb_xr/tokenization/compression.py
Overview
VQ-VAE-based tokenization for discrete DHB invariant representations.
Main Classes
DHBTokenizer
DHBTokenizer
Bases: Module
Causal VQ-VAE for invariant sequences. invariants (B, T, C) -> tokens (B, T), reconstructed (B, T, C).
Source code in src/dhb_xr/tokenization/vqvae.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
Functions
decode_from_latent
Decode from continuous latent to invariants.
Bypasses the VQ step, useful for flow matching generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Continuous latent (B, T, latent_dim). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed invariants (B, T, invariant_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
decode_tokens
Decode token indices to invariants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Tensor
|
Token indices (B, T). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed invariants (B, T, invariant_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
embed_tokens
Convert token indices to embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Tensor
|
Token indices (B, T). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Token embeddings (B, T, latent_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
encode_continuous
Encode invariants to continuous latent space (before quantization).
This is useful for flow matching which operates in continuous space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invariants
|
Tensor
|
Input invariant sequences (B, T, C). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Continuous latent z (B, T, latent_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
get_codebook_embeddings
Get the VQ codebook embeddings.
Useful for flow matching in embedding space or visualization.
Returns:
| Type | Description |
|---|---|
Tensor
|
Codebook embeddings (codebook_size, latent_dim). |
Source code in src/dhb_xr/tokenization/vqvae.py
quantize
Quantize continuous latent to discrete tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Continuous latent (B, T, latent_dim). |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (indices, z_q_st, z_q). |
Usage Example
import torch
from dhb_xr.tokenization.vqvae import DHBTokenizer
# Create tokenizer
tokenizer = DHBTokenizer(
invariant_dim=8,
latent_dim=16,
codebook_size=64
)
# Tokenize invariants
invariants = torch.randn(10, 20, 8) # (batch, time, features)
tokens = tokenizer.encode(invariants)
# Decode back
reconstructed = tokenizer.decode(tokens)