mixle.represent package¶
The representation layer – embed any modality into one shared space; discretize it only if (and how) you want.
The tokenizer question, resolved by not fixing a vocabulary. Three separable pieces:
segment– aSegmentercuts raw data (text, image, signal, sequence, structure) into units, committing to a decomposition but no vocabulary;
embed– anEmbeddingmaps each unit into sharedR^dim(a lookup table for a discrete unit, a small encoder for a continuous one), sharable/tie-able across models;
quantize– an optional, learnedVectorQuantizerturns the shared vectors into discrete ids in the embedding space, so a codebook (a “vocabulary”) is fit to the data – and can be shared across modalities – rather than guessed.
HeterogeneousEncoder composes per-modality (segmenter, embedding)
pairs into one (N, dim) stream a single downstream model consumes – trainable to a generative or a downstream
objective, so “the right tokenization” is inferred under the objective rather than fixed upfront.
- class PosteriorRetriever(model, corpus, *, evidence_cap=1.0, field_weights=None)[source]
Bases:
objectRetrieve over raw heterogeneous records by the fitted mixture’s posterior affinity.
- Parameters:
model (Any)
corpus (Any)
evidence_cap (float | None)
field_weights (Any)
- affinity_matrix()[source]
The corpus’s dense
(n, n)log-affinity matrix (diagonal-inf).- Return type:
- retrieve(query, k=5)[source]
Top-
kcorpus records for one query:[(corpus_index, log_affinity), ...]best first.
- class AutoencoderResult(encoder, decoder, quantizer, losses=<factory>)[source]
Bases:
objectA generatively-trained representation: the encoder, its decoder, an optional codebook, and the loss curve.
- Parameters:
- encoder: FeatureEmbedding
- decoder: Any
- quantizer: VectorQuantizer | None
- class ByteSegmenter[source]
Bases:
SegmenterA string/bytes ->
(n,)byte ids in[0, 256). The vocabulary-free text decomposition.- discrete: bool = True
- num_categories = 256
- class CategoricalEmbedding(num_categories, dim, *, name=None)[source]
Bases:
objectA lazily-built learned embedding of shape
(num_categories, dim); every consumer gets the same module.
- class Embedder(featurizer, result, kind, corpus_vectors)[source]
Bases:
objectA fitted embedding of raw heterogeneous items:
transformto vectors,retrieveneighbours.- Parameters:
featurizer (Any)
result (AutoencoderResult)
kind (str)
corpus_vectors (np.ndarray)
- property dim: int
- transform(items)[source]
Embed items into the learned space, unit-normalized (so dot = cosine similarity).
- retrieve(query, k=5)[source]
Top-
kfitted-corpus neighbours ofqueryas(corpus index, cosine similarity).
- class ElementSegmenter(alphabet)[source]
Bases:
SegmenterA sequence of hashable symbols (chars, amino acids, k-mers, categories) ->
(n,)ids via a fixed alphabet.Given
alphabet(the ordered symbols), each element maps to its index; unknown symbols map to0. The natural decomposition for proteins/genomes/any categorical sequence, and for characters (alphabet=list(...)).- Parameters:
alphabet (list[Any])
- discrete: bool = True
- class FeatureEmbedding(in_features, dim, *, hidden=(), name=None)[source]
Bases:
objectA continuous unit encoder:
(n_units, in_features) -> (n_units, dim)via a linear or small-MLP module.The continuous analogue of
CategoricalEmbedding– samedim/.module()contract, so it shares and trains identically.hidden=()is a single linear projection (a learned patch/ window/element embedding); non-emptyhiddeninserts ReLU layers.
- class GraphEmbedding(in_features, dim, *, layers=2, name=None)[source]
Bases:
objectA message-passing embedding:
(node_features, adjacency) -> (n_nodes, dim)withlayersGCN rounds.
- class GraphEncoder(embedding)[source]
Bases:
ModalityEncoderA structure modality:
raw = (node_features (n, f), adjacency (n, n))-> per-node vectors in sharedR^dim.- Parameters:
embedding (GraphEmbedding)
- encode(raw)[source]
Torch tensor
(n_units, dim)– gradients flow to the embedding (and, via it, train the encoder).
- class HeterogeneousEncoder(dim)[source]
Bases:
objectA registry of per-modality encoders sharing one
dimspace, plus a learned modality-type embedding.- Parameters:
dim (int)
- register(modality, segmenter, embedding)[source]
Add a modality’s
(segmenter, embedding); the embedding’sdimmust match the shared space.
- register_encoder(modality, encoder)[source]
Add a pre-built
ModalityEncoder(e.g. aGraphEncoderthat owns its own segment+embed path).- Parameters:
modality (str)
encoder (ModalityEncoder)
- Return type:
HeterogeneousEncoder
- encode(record)[source]
A record
{modality: raw}->(stream, modality_ids): one(N, dim)tensor + each unit’s source id.Each modality’s units are embedded and the modality-tag vector is added, then all are concatenated in registration order – the unified token stream for a downstream model.
- encode_numpy(record)[source]
- class LearnedSegmenter(atomic, n_states=4, *, max_its=30, seed=0)[source]
Bases:
SegmenterCut a raw object into variable-length tokens at HMM state changes over its atomic units (pooled to features).
- discrete: bool = False
- fit(raws)[source]
Fit the boundary HMM on example raws – the segmentation is learned to maximize their likelihood.
- class ModalityEncoder(segmenter, embedding)[source]
Bases:
objectOne modality’s
raw -> (n_units, dim)path: a segmenter feeding an embedding into the shared space.- Parameters:
segmenter (Any)
embedding (Any)
- encode(raw)[source]
Torch tensor
(n_units, dim)– gradients flow to the embedding (and, via it, train the encoder).
- class PatchSegmenter(patch=8)[source]
Bases:
SegmenterAn image
(H, W)or(C, H, W)->(n_patches, patch_features)float units (ViT-style, no vocab).- Parameters:
patch (int)
- discrete: bool = False
- class Segmenter[source]
Bases:
objectBase:
segment(raw) -> np.ndarray.discretesays whether units are ids (vs. float features).- discrete: bool = False
- class SetSegmenter[source]
Bases:
SegmenterA set/list of feature vectors ->
(n_elements, feat): nodes of a graph, atoms of a molecule, taxa of a section.The general structured-object decomposition – a scientific structure becomes its set of element features (which a downstream model can further couple with a structure/message-passing embedding).
- discrete: bool = False
- class VectorQuantizer(num_codes, dim, *, seed=0)[source]
Bases:
objectA learned codebook over
R^dim: nearest-centroid quantization of embedding vectors into discrete ids.- fit(vectors, *, iters=25)[source]
Fit the codebook by k-means (Lloyd) on
vectors(n, dim)– the vocabulary is learned, not assumed.
- quantize(vectors)[source]
Nearest-code id for each vector – the discrete token stream
(n,).
- dequantize(ids)[source]
Codebook vectors for token ids
(n,)->(n, dim)(the reconstruction / de-tokenization).
- reconstruction_error(vectors)[source]
Mean squared quantization error – the codebook’s fidelity (a codebook-size / bitrate knob).
- straight_through(vectors)[source]
VQ-VAE straight-through estimator: return quantized vectors but pass gradients to
vectorsunchanged.Lets the encoders and (with a codebook-commitment loss) the codebook train end to end through the discrete bottleneck.
vectorsis a torch tensor(n, dim).
- class WholeSegmenter[source]
Bases:
SegmenterA single feature vector ->
(1, feat): the object is one unit (a pooled structure descriptor, a record).- discrete: bool = False
- class WindowSegmenter(window=64, hop=None)[source]
Bases:
SegmenterA 1-D signal
(T,)->(n_frames, window)float units by a sliding window (seismic/audio/time-series).- discrete: bool = False
- fit_autoencoder(units, dim, *, hidden=(), quantizer=None, epochs=200, lr=1e-2, refit_codebook_every=25, commitment=0.25, seed=0)[source]
Train an encoder+decoder to reconstruct
units(N, in_features); optionally through a VQ bottleneck.Without
quantizerthis is a plain autoencoder (the encoder becomes a generative representation). With one, it is a VQ-VAE: the encoder’s vectors are quantized (straight-through) before decoding and the codebook is refit everyrefit_codebook_everyepochs on the current embeddings, so the learned vocabulary adapts to the representation.commitmentweights the VQ codebook-commitment term.
- fit_embedder(data, dim=32, *, kind=None, feature_dim=256, hidden=(64,), epochs=200, lr=1e-2, seed=0)[source]
Fit a learned embedding of raw text or record items and return an
Embedder.Items featurize deterministically (hashing trick; no fitted vocabulary), then an autoencoder learns a
dim-dimensional generative representation of the corpus.retrieveworks out of the box over the fitted data;transformembeds anything of the same kind.
- vectorize(item, kind, *, dim=16, embedder=None)[source]
Map a raw
itemof modalitykindto a fixeddimvector (see module docstring).- Parameters:
item (Any) – the raw item (a string, a record, an image array, a signal array).
kind (str) –
'text'|'record'|'image'|'signal'.dim (int) – output vector dimension.
embedder (Any) – for
text/record, a fittedEmbedderto reuse (else a small one is fit on the single item – pass one for consistency across a corpus).
- Return type:
- vectorize_all(items, kind, *, dim=16)[source]
Vectorize a sequence of same-modality items to an
(n, dim)array (one shared embedder for text).
- image_features(img, dim=16, *, grid=None)[source]
A fixed
dimdescriptor of an image: mean intensity over ag x ggrid of cells.imgis(H, W)or(H, W, C); channels are averaged. The grid sidegis chosen sog*gcoversdim(then truncated/padded to exactlydim), giving a coarse spatial-layout vector – enough for an image field to correlate with structured fields in a discovered graph.
- signal_features(sig, dim=16, *, windows=None)[source]
A fixed
dimdescriptor of a 1-D signal: (mean, energy, range) over evenly-spaced windows.
Submodules¶
- mixle.represent.api module
- mixle.represent.embed module
- mixle.represent.generative module
- mixle.represent.graph module
- mixle.represent.heterogeneous module
- mixle.represent.learned_segment module
- mixle.represent.modality module
- mixle.represent.posterior module
- mixle.represent.quantize module
- mixle.represent.segment module