Kongming HV
kongming is a library implementing operations on sparse binary hypervectors for cognitive computing applications.
While ergonomic APIs are accessible via Python module of kongming for better usability, the core engine is explored in Go for flexibility before being ported to Rust for maximum efficiency.
See Concepts for an introduction to hyperdimensional computing and, more relevant to this package, the sparse binary representation and computation.
License
The Python source code, examples, and documentation in this repository are licensed under the MIT License.
However, the core engine distributed via PyPI (kongming-rs-hv) is proprietary, talk to me if you have further questions.
Install
pip install kongming-rs-hv
See Installation for supported platforms and verification steps.
Published notebooks
See Notebook Platforms for all available notebooks and platform details.
Guides
| Guide | Description |
|---|---|
| Python Quick Start | Installation, examples, and walkthrough |
| Notebook Quick Start | Platform setup, interactive notebooks, cell-by-cell walkthrough |
Language Support
This documentation covers code snippets in multiple languages (if available) side by side.
- Python: bindings to the underlying Rust implementation (public
kongming-rs-hvon PyPI); - Go: canonical / reference implementation in proprietary package;
- Rust: parallel implementation, carefully maintained in feature parity;
Docs versioning
The documentation on yangzh.github.io/hv stays in lockstep with the latest kongming-rs-hv release on PyPI. Whatever you read there matches what pip install kongming-rs-hv gives you.
The main branch of this repository, however, is the working head: it may describe APIs or examples that haven’t been released yet: if you browse the raw markdown on GitHub, expect it to occasionally be ahead of the published site.
Reference
The work was initially outlined in this arxiv paper, built on top of the work from many other authors. Here is the citation:
Yang, Zhonghao (2023). Cognitive modeling and learning with sparse binary hypervectors. arXiv:2310.18316v1 [cs.AI]
Feedback
Found a bug, have a question, or want to suggest an improvement? Open an issue on GitHub.
Concepts
The ideas behind this library, independent of any particular language binding. Start here for the mental model; jump to the API Reference for the concrete surface and practical usage.
Hyperdimensional Computing (HDC) and Vector Symbolic Architectures (VSA) are two names for the same field. These docs use VSA when referring to the algebra of operators.
| Concept | Description |
|---|---|
| Hypervectors | High-dimensional vectors, similarity and distance |
| Operators | Bind and bundle: the algebra of composition |
| Composites | Structures built from the primitives |
| Near-neighbor search | Highly efficient retrieval of relevant entries |
| Learner | Hebbian learning over a stream of experience: bedrock for intelligent behaviors |
| LearnerPool | Pooled Learners sharing a fixed budget elastically |
| HyperPhaser | Bundling offsets as phases rather than labels: FHRR in the offset representation |
Hypervectors
What is Hyperdimensional Computing?
Hyperdimensional computing (HDC) represents concepts as high-dimensional vectors (also called hypervectors) and manipulates them with algebraic operations, typically the dimension (of vectors) can be as high as thousands or millions.
The key insight is that random vectors in high-dimensional spaces are nearly orthogonal: giving each concept a unique, robust representation that tolerates potential ambiguity and interference, all without central orchestration.
In that sense, the traditional mantra of curse of dimensionality becomes the blessing of dimensionality.
Motivated readers should perform their own background research on this topic and make judgement of their own. There are many introductory papers covering this topic of hyperdimensional computing, or equivalently VSA (Vector Symbolic Architecture).
Sparse Binary Representation
kongming specializes in sparse binary hypervectors. Each vector has a fixed, large number of dimensions (e.g., 65,536/64K or 1,048,576/1M), but only a very small fraction of them are “on” (set to 1). The sparsity is controlled by the Model configuration.
Furthermore, we focus on a special sparse binary arrangement, where each vector is divided into equal-sized segments, and exactly one bit is ON per segment. For example, each of the 8bit-model hypervectors will have total dimension of , divided into segments, where each segment of dimension will have one (and only one) ON bit.
Alternatively you can imagine each hypervector as a list of phasors, where the offset of ON bit (within the host segment) represents the discretized phase of a unit circle. For the above-mentioned 8bit models, each hypervector will have such phasors, each with discrete phases around the unit circle, ranging over .
In general, this unique constraint enables:
- Compact storage: only the offsets of ON bit are needed, which is exactly the minimal entropy for the representation;
- Efficient operations: Unlike neural nets where weights are recorded in float-point numbers, binary/integer operations can be performed very efficiently with modern memory / CPUs, and without the need of GPU for either float-point operations or matrix manipulations.
Similarity and distance measure
Two vectors are compared via overlap — the count of segments with the same ON bit offset. This is conceptually equivalent to a dimension-wise AND operation.
For a model (for example, 8bit model), with dimension and sparsity :
Naturally, a vector’s overlap with itself equals its cardinality .
The overlap (of random vectors and ) follows a Poisson distribution with , so the expectation follows:
The commonly-used distance measure (or dis-similar measure) for binary vectors is Hamming distance, equivalent to a bitwise XOR operation.
As we discussed (and proved) in the paper, the overlap and Hamming distance for sparse binary hypervectors are two sides of the same coin, with the following equation:
the more overlap they have, the closer two vectors in Hamming space.
To visualize this, we have two random 8-bit hypervectors drawn over the same grid. Each of the segments contributes one dot, placed inside its own segment group at the offset of that segment’s ON bit — red for the first vector, blue for the second. The heavy grid lines delimit the segment groups, while the fine ones are individual offsets.
This is what near-orthogonality looks like: two vectors drawn independently from a -dimensional space, agreeing by coincidence on a single segment out of — and nowhere else.
Lee distance: the graded alternative
Both measures above are binary per segment: two offsets either agree or they
do not, and an offset one step away counts exactly like one on the far side of
the ring. That is the honest reading for a Sparkle, whose offsets are
independent random draws — “how far apart” is noise.
But recall the phasor view: an offset is a discretized phase. Where an offset carries an ordinal meaning, the gap between two of them is real information, and Lee distance reads it — the circular gap for a segment of positions, averaged over the segments:
Like Hamming distance, Lee distance is also a distance metric. Reported per segment, so it is comparable across models: chance is and the maximum whatever is. Two offsets one step apart contribute , where Hamming would already charge the full penalty.
Lee is NOT a restatement of overlap the way Hamming is. Overlap only ever asks whether two offsets match, never how far apart they are, so it constrains Lee only loosely — two vectors of identical overlap can sit at very different Lee distances.
Supported Models
A Model is named for its one free parameter: the segment size in bits. Cardinality equals the segment size, so an -bit model carries offsets of bits each — and a HyperPhaser carries phasors on a ring of . The binary width follows from that one choice and matters only to the binary form; the storage and compute characteristics follow from all three.
| Model | Width | Sparsity Bits | Cardinality | Segment Size |
|---|---|---|---|---|
MODEL_8BIT | 65,536 | 8 | 256 | 256 |
MODEL_10BIT | 1,048,576 | 10 | 1,024 | 1,024 |
MODEL_12BIT | 16,777,216 | 12 | 4,096 | 4,096 |
MODEL_14BIT | 268,435,456 | 14 | 16,384 | 16,384 |
MODEL_16BIT | 4,294,967,296 | 16 | 65,536 | 65,536 |
Model properties
All model functions take a Model enum value and return the derived property:
For simplicity, we use function names from Python. The counterparts from Go / Rust can be found by consulting their respective references.
| Function | Description |
|---|---|
width | Total dimension count (2^width_bits) |
cardinality | Number of ON bits (= number of segments) |
sparsity | Fraction of ON bits (1 / segment_size) |
segment_size | Dimensions per segment |
How to Choose a Model
MODEL_8BIT: Fast prototyping, with minimal memory footprint and high performance (due to SIMD). Good for tests, experiments and production.MODEL_10BIT: General-purpose, balances performance and storage.MODEL_12BIT: General-purpose, for the adventurous.MODEL_14BIT/MODEL_16BIT: Very high capacity, not there yet.
In general, larger models provide more orthogonal space (lower collision probability) at the cost of more memory per vector.
The storage consideration above applies to SparseSegmented, the particular type containing raw offsets. There are other types of sparse binary hypervector, typically defined by a recipe: a seed, or a seed plus members, and carries only that instead of raw offsets. For example, Sparkle stores its seed and derives its offsets on demand; composites such as Set and Sequence hold references to their members, so they cost far less than a materialized vector both in memory and on the wire.
Additionally, the bits are computed on first observation and cached, then released again on compact(). Constructing a vector you never observe therefore costs almost nothing — see lazy materialization.
Operators
kongming provides two core algebraic operations on sparse binary hypervectors.
Bind
Binding () combines two vectors into a result that is dissimilar to both inputs. It is the multiplicative operation in the VSA algebra.
Definition
For codes , bind is segment-wise modular addition of the ON offsets:
where is the offset of the ON bit in the -th segment of . Each segment is handled independently, so the result keeps exactly one ON bit per segment — binding never leaves the segmented space.
Mathematically
Implementation: segment-wise offset addition modulo segment size .
Check out original paper for details.
Check out code snippets from the API reference.
Release
Occasionally we use release, as the equivalent of division.
Note that release is anti-commutative:
Check out code snippets from the API reference.
Bundle
Bundling () creates a superposition of vectors, which is similar to all inputs. It is the additive operation in the VSA algebra.
Definition
For codes with normalized weights (where ):
Bundling is not arithmetic addition. Each segment of the result takes its offset from exactly one operand, chosen with probability :
So every segment still holds exactly one ON bit, and the result stays in the segmented space. Think of it as a lossy compression: retains each operand’s segment-wise offsets in proportion to that operand’s weight, which gives the similarity directly:
With uniform weights , the notation simplifies to the plain sum and each member keeps a share:
This is the capacity limit in one line: bundle members and each survives at overlap , so a member stops being recoverable once approaches the noise floor.
Mathematically
Check out original paper for details on bundle operator.
Check out code snippets from the API reference.
Composites
Composites combine multiple hypervectors into higher-level conceptual structures. Each composite type uses a different combination strategy, preserving different semantics between its members.
Sparkle ✨: the primitive
Before any composite, there is the Sparkle ✨: the atomic, seeded hypervector everything below is built upon.
A raw SparseSegmented 🍡 is just a bit pattern. A Sparkle ✨ is a deterministic hypervector built from a seed of two parts:
- the Domain — a semantic namespace, such as “animals”, “role”, or “country”;
- the Pod — the individual within it: a word, a numeric seed, or a constant pre-defined by the package.
That pair seeds an underlying RNG (random number generator), which deterministically produces the vector’s offsets. The same model, domain and pod therefore yield the same Sparkle ✨ in every run and every engine, with Go, Rust, and Python bit-identical. Carrying that seed instead of the raw per-segment offsets is also a significant saving, both on the wire and in storage.
Two properties that carry the most weight:
- The tuple of (Domain, Pod) can be treated as the unique identity for the Sparkle ✨;
- Distinct Sparkles ✨ are always nearly orthogonal, without any central orchestration. They can be safely used as bricks for high-level construction;
This one primitive is also what the composite algebra is built from: the markers and keys in the formulas below — , , — are themselves Sparkles ✨, so every structure on this page bootstraps from the same type.
Use when: you need a stable, deterministic identity for an atomic concept, like a word, a role, an entity, or as a leaf for the composites below.
Check out code snippets from the API reference.
Set 🫧
An unordered collection of concepts.
where is a special marker (predefined Sparkle ✨) that causes the different encoding between individual element and the set .
Use when: you need to represent “these things together” without order.
Check out code snippets from the API reference.
Sequence 📿
An ordered collection.
where is a special marker (predefined Sparkle ✨) for positional encoding.
is a special marker such that an element and the sequence are encoded differently.
Use when: order matters (e.g., words in a sentence, events in time).
Check out code snippets from the API reference.
Octopus 🐙
A key-value structure. Each key (a string) is converted to a Sparkle ✨ and bound with its corresponding value before bundling.
Use when: you need to represent structured records with named attributes.
Check out code snippets from the API reference.
Knot 🪢
The result of binding (multiplicative composition) of hypervectors.
Unlike direct bind operator, Knot 🪢 keeps tracking of its members for serialization and introspection.
Use when: you need a reversible association between concepts.
Check out code snippets from the API reference.
Parcel 🎁
The result of bundling (additive composition) of hypervectors.
Unlike direct bundle operator, Parcel 🎁 keeps tracking of its members for serialization and introspection.
Use when: you need a superposition of concepts, with optional weights.
Check out code snippets from the API reference.
Dart 🎯
A one-directional reference between two hypervectors.
A Dart 🎯 is “thrown” from a tail T to a head H — the direction is semantic (T → H), while algebraically the link is recoverable from either end. Dart 🎯 is the structured wrapper for the release.
Given the Dart 🎯 of :
Use when: you need a directed link — edges, mappings, “from→to” relations — where either endpoint can still be recovered given the other.
Check out code snippets from the API reference.
Summary
All composites follow the same contract (interface in Go and traits in Rust) and can be hierarchically nested: for example, a Set can contain Sparkles, Knots, or even other Sets.
Here are some of the important subtypes of hypervectors supported in this package:
| Type | Composition | Order? | Use Case |
|---|---|---|---|
| SparseSegmented | None — raw per-segment offsets | — | The materialized form every other type reduces to |
| Sparkle | Primitive — seed expansion, no members | — | Named atomic identities |
| Set | set of primitives | No | Unordered groups |
| Sequence | sequence of primitives | Yes | Ordered lists |
| Octopus | Key-bind + bundle | No | Key-value records |
| Knot | Bind (multiply) | No | Associations |
| Parcel | Bundle (add) | No | Superpositions, weighted or unweighted |
| Dart | Release | Directional | One-directional references |
| Learner | Online bundling | No | Learning distributions: frequencies, co-occurrence |
| Point | Fractional Power Encoding | — | Positions in a continuous frame |
Near Neighbor Search
Near Neighbor Search (NNS) retrieves chunks from the storage substrate in increasing order of Hamming distance (from a query).
As we mentioned earlier, this is equivalent to strictly descending overlap (between query and candidate). Overlap generally encodes semantic relevance, and this translates to a list of semantically relevant candidates, most relevant one first.
This NNS module has linear time complexity (with respect to the entry count indexed) with a very low constant — in expectation only a few tally operations per stored entry — so query cost grows gently with the number of entries in the storage substrate.
It leverages an underlying Associative Index for efficient recovery of candidates. The Associative Index is a semantic index that enables fast similarity-based lookup over stored hypervectors. Conceptually it turns a key-value substrate into an associative memory — one where retrieval is by content similarity, not by exact content or key match.
Unlike approximate nearest neighbor methods (LSH, HNSW, etc.), the choice of sparse and binary hypervectors makes this exact and efficient. The NNS module computes exact overlap counts via the associative index. There is no approximation error and no index-specific parameters to tune.
Jump to the API reference for Near-Neighbor Search.
Learner
A Learner performs online bundling over a stream of observations, in the style of Hebbian learning: each incoming pattern claims a share of a fixed representational budget, weighted by how often it is seen.
Conceptually the Learner itself is a single hypervector whose content is the weighted superposition of everything it has experienced; recovery runs through the NNS (a.k.a. the near neighbor search module) against all known patterns: frequent patterns read back with shorter distance / higher overlap, rare ones faintly with larger distance / lower overlap.
The fixed representational budget
A Learner is not a pure container for all experiences but a distribution that sharpens or flattens, which makes it ideal for learning distributions: transition frequencies, co-occurrence statistics — and gives it a natural capacity, beyond which no experiences can be reliably recovered.
To give you a concrete example, an 8bit learner, at its core, is a sparse binary hypervector with segments, each containing a single ON bit. Given the inherent noise, only a few dozen unique patterns can survive the dilution and maintain recognizable weights to be picked up by the NNS module. Within its own working range, different patterns claim their own share among the same segments, with respect to their relative weight: in this sense, the Learner is self-normalized.
This fixed representational budget ( segments) is what gives a Learner its character, and most critically, the limitation we will address later in LearnerPool.
Jump to the API reference for Learner.
LearnerPool
LearnerPool is an aggregate over member Learners for improved scalability. Instead of dedicating one Learner to one particular use case, a pool holds a fixed roster of member Learners that can collectively support many learning tasks in parallel.
Each learning task is identified by a particular address, so the conceptual design goal is to have a Learner-like component where an observation can be written into a given address, and with improved capacity.
The solution LearnerPool takes is to return a small access circle of member Learners for each addressed access, which can expand based on actual need.
Why a pool
A single Learner has a hard capacity ceiling: as more distinct patterns are experienced, each pattern’s share of ON bits dilutes, until they become indistinguishable from random noise. This can happen past a few dozen unique patterns for an 8bit Learner, for example.
This capacity limitation (of the classic Learner) bites in various scenarios:
- high fan-out addresses saturate and silently forget everything;
- the long tail of low fan-out addresses wastes almost all of their dedicated capacity.
A pool solves both issues exactly as its name suggests, by pooling many Learners together. Most light addresses still get a nearly-private member, while heavy addresses recruit as many members as their content genuinely needs, up to the whole pool. At the end of the day, an individual member can serve a mixture of low and high fan-out addresses, orchestrated internally by the pool’s own scheduling logic. As far as the pool is concerned, the overall storage budget is fixed at construction time, and won’t grow unbounded as we have more learning tasks.
The internal “orchestration” (or rewiring) is mathematically sound, stable, and requires no manual intervention. The member Learners organize organically rather than piling up naively: if each Learner were a basic “neuron”, a LearnerPool is then akin to an organism that behaves intelligently and coherently toward a common goal.
Fixed resource consumption
Unlike the naive arrangement of one Learner per learning task which can grow unbounded for new tasks, a LearnerPool uses a fixed amount of resources: entities of varying fan-out intelligently share the same pool.
The roster size is set at pool creation and won’t grow afterwards: there is currently no incremental expansion short of a full retrain. When every member a write could reach is full, the pool refuses the write rather than degrade what it already holds.
So another way to understand LearnerPool: it’s an addressable collection of elastically scalable (up to the fixed pool capacity) Learners, built upon a fixed grid of classic Learners.
Recruiting member Learners
The LearnerPool recruits a suitable member Learner by ensuring the incoming pattern can be recalled reliably later.
The pool’s scheduler always tries to locate one suitable member, unless the whole pool is out of capacity, in which case the write will fail. In the extreme case, all members can be used as reserves as needed.
Using bigger learners
Using bigger Learners (for example, 10bit, 12bit, etc.) is a completely orthogonal direction for expanding capacity. However, adding more members can be straightforward, and most of the time more effective.
Another practical consideration: 8bit offsets are byte-aligned (one byte per segment; 16bit is two), which unlocks low-level SIMD on all supported platforms and boosts performance significantly. 10bit/12bit/14bit offsets are not byte-aligned and do not vectorize this way: so stick with 8bit if you care about performance.
Jump to the API reference for LearnerPool.
HyperPhaser
A HyperPhaser bundles a stream of observations, much like a Learner does — but it reads each offset as a phase rather than as a label, and that one change of interpretation changes its character throughout.
Recall from Hypervectors that a sparse-segmented vector is already a list of phasors: the offset of the ON bit within its segment is a discretized phase around the unit circle. A Learner treats that offset as an opaque identity and only ever asks whether two of them match. A HyperPhaser takes the phasor reading literally — it superposes unit phasors and keeps the resulting angle.
For segment of a vector with segment size , an observation contributing offset with weight enters as a unit phasor at angle , and the accumulator holds the complex sum:
This is FHRR — Plate’s complex-valued VSA — expressed in the offset representation kongming already uses. The stored offset for segment is simply quantized back onto the ring, so the result is an ordinary sparse-segmented vector that composes under bind like any other.
What it estimates
Comparing two phasor bundles estimates the cosine between the weight vectors underneath them:
The reason is that independent phases cancel on average: the cross terms between unrelated observations vanish, leaving only the mass the two bundles genuinely share. Each segment is one noisy estimate of that quantity, and averaging over of them tightens the estimate with standard error .
That single fact sets the expectations. The readout is scale-free — re-presenting the same data changes the magnitudes but not the angles, so it does not drift. It is flat in the number of distinct observations, because a cosine cares about alignment rather than how many things contributed. And it sharpens with larger , where the extra segments buy ranking resolution rather than fidelity: a pairwise comparison is already unbiased at small , but telling the best match from the tenth-best among many thousands of candidates needs the tighter error.
Accumulating versus sampling
The contrast with a Learner is the useful way to hold this. A Learner is a sample: each write draws on randomness to claim a share of a fixed budget of segments. A HyperPhaser is an accumulator: every write adds deterministically into every segment.
| Learner 💫 | HyperPhaser 🧭 | |
|---|---|---|
| write | reservoir sampling, draws randomness | deterministic and linear |
| repeated observation | a fresh draw | identical to one write at double weight |
| a member owning less than | invisible, it won no segments | still moves every segment |
| compared by | Hamming distance | Lee distance, or alignment |
Determinism and linearity are what make the small shares survive. Because a Learner is a sample, a member too faint to win a single segment is simply absent from it; because a phasor accumulates, even a tiny weight nudges every angle a little, and the bundle as a whole still carries it.
Which distance to ask for
Treating offsets as phases changes which distance measure is meaningful, and this is the sharpest practical consequence of the whole idea.
Two phasors one ring step apart are maximally similar, yet they share no exact offset. Overlap and Hamming distance are blind to that: they are binary per segment, so they read those two phasors as no more related than a pair on opposite sides of the circle. Lee distance reads the circular gap instead, and on unit phasors it induces the same ranking as the complex cosine, being monotone in the phase gap over the half-period. Alignment reads the cosine directly.
Every hypervector answers all of them, so the choice is yours to make and yours to get wrong. A bundle you intend to read as phases must not be fed to the overlap-keyed near-neighbor search — the index would answer at chance. The bytes of a quantized phasor vector are indistinguishable from any other sparse-segmented vector’s, so nothing can carry that warning for you at the call site.
Two forms, one direction
The accumulator and the thing you store are deliberately separate — and only the accumulator is a distinct type, because every hypervector is already a vector of phasors.
A HyperPhaser is the trainable form: a dense complex accumulator holding components, each with an angle and a magnitude. It is not itself a hypervector and has no wire format. The magnitude matters while training — it is a per-segment confidence, recording how much the contributing phases reinforced or cancelled there, and a segment whose phases nearly cancelled holds an angle decided by rounding residuals rather than by evidence. It also behaves as per-segment plasticity.
quantize() crosses to the published form: one angle per segment, an ordinary sparse-segmented vector. It goes one way and keeps angles only — so the per-segment confidences live on the accumulator, and a caller who wants them keeps them alongside deliberately.
Jump to the API reference for HyperPhaser.
HV
The core hypervector API. This module provides the building blocks for hyperdimensional computing: vector types, algebraic operators, and model configuration.
| Section | Description |
|---|---|
| Common Utilities | Model, SparseOperation, similarity, identity, hashing |
| Operators | Bind, bundle, and BindDirect |
| HyperBinary Types | Interface + concrete types (Sparkle, Set, Sequence, etc.) |
| Customizing Run-time Behavior | Environment variables |
| Misc | Display, serialization |
Common Utilities
Functions and types used across all HyperBinary types.
| Section | Description |
|---|---|
| Models | Model enum and model functions |
| SparseOperation | Model + seeded RNG for deterministic vector generation |
| Seed128 | 128-bit seed embedding Domain + Pod |
| Domain & Pod | Semantic grouping (Domain) and slot identifier (Pod) |
| Utilities | Similarity, identity check, hashing |
Models
A model is named for its segment size in bits: MODEL_8BIT divides the space into
segments of 256 offsets, and carries 256 of them. The binary width follows from that
one number (65,536 here) and is deliberately not part of the name — it describes the
binary form alone, and says nothing about a HyperPhaser over the
same model.
See Concepts: Hypervectors for the full overview.
Model Enum
model0 = hv.MODEL_8BIT
model1 = hv.MODEL_10BIT
Model Functions
hv.width(hv.MODEL_10BIT) # total dimensions
hv.cardinality(hv.MODEL_10BIT) # ON bit count
hv.sparsity(hv.MODEL_10BIT) # sparsity
hv.segment_size(hv.MODEL_10BIT) # dimensions per segment
See also: SparseOperation — Model + seeded RNG for deterministic vector generation.
Domain & Pod
A Domain models the semantic grouping for hypervectors, providing the high 64-bit half of a Seed128. A Pod is a slot within a Domain, providing the low 64-bit half. The (Domain, Pod) pair uniquely identifies a Sparkle.
Domain Constructors
# From a name string (hashed to a 64-bit id)
d = hv.Domain("animals")
# Same as above
d = hv.Domain.from_name("animals")
# From a raw 64-bit id
d = hv.Domain.from_id(0x1234567890abcdef)
# From a domain prefix enum and a name suffix
# The id is computed as xxhash(prefix_label + "." + name)
d = hv.Domain.from_prefix_and_name(hv.DOMAIN_PREFIX_NLP, "concept")
# Accessors
d.id() # u64
d.name() # str (empty if constructed from id)
d.domain_prefix() # int (0 = UNKNOWN if no prefix was set)
d.is_default() # True if id == 0
Domain Prefix Constants
| Constant | Label |
|---|---|
hv.DOMAIN_PREFIX_USER | 🎭 |
hv.DOMAIN_PREFIX_NLP | 💬 |
Domain prefixes provide namespacing for domains. When a prefix is set, the domain id is derived from the prefix label (and optional name), ensuring consistent hashing across languages.
Pod Constructors
Pods can be seeded by a string word, a raw uint64, or a prewired enum value.
# From a word string (hashed to a 64-bit seed)
p = hv.Pod("cat")
# Same as above
p = hv.Pod.from_word("cat")
# From a raw 64-bit seed
p = hv.Pod.from_seed(42)
# From a prewired enum value
p = hv.Pod.from_prewired(hv.PREWIRED_SET_MARKER)
p = hv.Pod.from_prewired(hv.PREWIRED_STEP)
# Accessors
p.seed() # u64
p.word() # str (empty if constructed from seed or prewired)
p.prewired() # int (0 if not prewired)
p.is_default() # True if seed == 0
Prewired Constants
Prewired pods are infrastructure-level constants with fixed seeds:
| Constant | Label |
|---|---|
hv.PREWIRED_NIL | ∅ |
hv.PREWIRED_FALSE | ❎ |
hv.PREWIRED_TRUE | ✅ |
hv.PREWIRED_BEGIN | 🚀 |
hv.PREWIRED_END | 🏁 |
hv.PREWIRED_LEFT | ⬅️ |
hv.PREWIRED_RIGHT | ➡️ |
hv.PREWIRED_UP | ⬆️ |
hv.PREWIRED_DOWN | ⬇️ |
hv.PREWIRED_MIDDLE | ⏺️ |
hv.PREWIRED_STEP | 𓊍 |
hv.PREWIRED_SET_MARKER | 🫧 |
hv.PREWIRED_SEQUENCE_MARKER | 📿 |
Polymorphic arguments (Python-only)
Most Python factories that take a Domain or Pod accept the
underlying primitives directly — you rarely need to wrap them
explicitly:
| Parameter type | Accepted Python forms |
|---|---|
Domain | Domain instance, str, int, (DomainPrefix, str) tuple |
Pod | Pod instance, Prewired enum, str, int |
# Domain — four equivalent forms in any factory expecting a Domain:
memory.by_item_key("animals", "cat")
memory.by_item_key(hv.Domain.from_name("animals"), "cat")
memory.by_item_key(0x1234, "cat") # from numeric id
memory.by_item_key((hv.DOMAIN_PREFIX_NLP, "concept"), "p") # from (prefix, name)
# Pod — Prewired enum is recognized:
memory.new_terminal("internal", hv.PREWIRED_STEP) # Pod from Prewired
memory.new_terminal("animals", "cat") # Pod from word
memory.new_terminal("animals", 0xCAFE_BABE) # Pod from raw seed
For the parallel polymorphism on Seed128, see
Seed128 → Polymorphic arguments.
Seed128
A Seed128 is a 128-bit seed to drive a random number generator.
The current random number generator expects 2 64-bit seeds: the same (seed_high, seed_low) pair always produces the same sequence of random numbers, enabling reproducible and deterministic vector generation across runs and languages.
Constructors
# From Domain and Pod arguments (each accepts Domain/Pod, int, or str)
seed = hv.Seed128("animals", "cat") # domain name + pod word
seed = hv.Seed128(0, 42) # default domain + raw pod seed
seed = hv.Seed128("animals", 42) # domain name + raw pod seed
seed = hv.Seed128(hv.Domain("animals"), hv.Pod("cat")) # explicit Domain/Pod objects
# Zero seed
seed_zero = hv.Seed128.zero() # (0, 0)
# Random seed from a SparseOperation
seed_rand = hv.Seed128.random(so) # consumes two u64 from the RNG
# Accessors
seed.domain() # Domain object
seed.pod() # Pod object
seed.high() # u64 (domain id)
seed.low() # u64 (pod seed)
Usage
All composite constructors take a Seed128, as seed for the bundle operator:
seed = hv.Seed128("fruits", "fruit_set")
s = hv.Set(seed, a, b, c)
seq = hv.Sequence(seed, a, b, c)
Polymorphic arguments (Python-only)
Anywhere a Python factory expects a Seed128 (composite constructors
like hv.Set / hv.Sequence / hv.Octopus, the hv.bundle operator,
etc.) you can pass either a Seed128 instance or a (domain, pod)
tuple — the binding extracts and constructs the seed for you.
| Parameter type | Accepted Python forms |
|---|---|
Seed128 | Seed128 instance, or a (domain, pod) tuple |
The tuple composes with the polymorphic forms accepted by Domain
and Pod (see
Domain & Pod → Polymorphic arguments),
so each side can itself be a string / int / Prewired enum / (prefix, name)
tuple — letting you skip the hv.Seed128(...) wrap entirely:
# Equivalent to hv.Sequence(hv.Seed128("words", "hi"), m1, m2):
seq = hv.Sequence(("words", "hi"), m1, m2)
# Tuple form composes with Domain's (DomainPrefix, str) tuple:
seq = hv.Sequence(((hv.DOMAIN_PREFIX_NLP, "concept"), "myseq"), m1, m2)
# And with Pod's Prewired enum:
seq = hv.Sequence(("internal", hv.PREWIRED_STEP), m1, m2)
SparseOperation
A SparseOperation instance wraps a Model, a random number generator, and potentially other information related to the sparse operation in general.
Constructor
so = hv.SparseOperation(hv.MODEL_10BIT, 0, 42)
# Explicit RNG backend (keyword-only; omit for the KONGMING_RNG default, hv.RNG_PHILOX_4X64)
# Constants: hv.RNG_PHILOX_4X64, hv.RNG_XOSHIRO_256PP, hv.RNG_PCG_DXSM, hv.RNG_XOROSHIRO_128PP.
so2 = hv.SparseOperation(hv.MODEL_10BIT, 0, 42, rng_hint=hv.RNG_XOSHIRO_256PP)
Methods
so.model() # Model enum
so.width() # width for this model
so.cardinality() # cardinality for this model
so.sparsity() # sparsity for this model
so.uint64() # next random number
so.rng_hint() # RNG backend (an hv.RNG_* constant)
Usage: Generating Random Vectors
so = hv.SparseOperation(hv.MODEL_10BIT, 0, 42)
sparkle = hv.Sparkle.random(hv.Domain("domain"), so)
Utilities
Similarity
hv.overlap(a, b) # Overlap: segments where the two agree, 0..M
hv.hamming(a, b) # Hamming distance: 2 * (M - overlap), 0..2M
hv.lee_distance(a, b) # Lee distance: mean circular gap, 0..W/2
hv.alignment(a, b) # Cosine similarity in angle space, -1..1
hv.equal(a, b) # Equality check
overlap and hamming carry the same information. A disagreeing segment flips
two bits — one off, one on — so hamming == 2 * (M - overlap) exactly, and
overlap == M - hamming // 2 back. Reach for whichever reads better; neither
is more precise than the other.
lee_distance is the graded one, and it answers a different question.
Where Hamming asks only whether two segments disagree, Lee asks how far apart their
offsets sit on the ring of W positions. That matters only where an offset
carries an ordinal meaning:
| use Hamming/overlap | use Lee | |
|---|---|---|
Sparkle, Learner, composites | yes — offsets are unrelated random draws, so “how far” is noise | no |
Point (fractional-power encoding) | yes, but it collapses to noise as positions separate | yes — graded in the coordinate gap |
a HyperPhaser.quantize() result | no — two phasors one step apart share no offset yet are nearly identical | yes — the offsets are phases |
Lee is reported per segment: the sum divided by M. That keeps it
comparable across models — chance is W/4 and the diameter W/2 whatever M
is. Two consequences worth knowing:
- shifting every offset by one is Lee
1, but the full Hamming diameter2M; - the division truncates, so a gap confined to a handful of segments reads
0. The resolution is one ring step, which suits a population readout and not the separation of near-identical vectors.
alignment reads the same ring gap as Lee and aggregates it the other way —
cosines rather than angles:
It is cosine similarity exactly: every segment contributes a unit phasor, so and the is precisely the normalization . From there, 1 - alignment is cosine distance (not a metric) and is the angular distance (which is). Use it when the natural answer is an inner product rather than a distance; lee_distance stays the integer metric.
Being a mean of cosines rather than a mean of angles, it does not determine Lee and Lee does not determine it — the two can order a pair differently, and neither is wrong.
Identity Check
v=hv.Sparkle.identity(model)
hv.is_identity(v) # True if v is an identity vector
Hash Utilities
hv.hash64_from_string("hello") # deterministic u64 hash from string
hv.hash64_from_bytes(b"\x01\x02") # deterministic u64 hash from bytes
hv.curr_time_as_seed() # current time as a u64 seed
hv.kongming_studio_seed() # fixed studio seed constant
HyperBinary Types
All vector types conform to a common HyperBinary interface, kept at feature parity across the underlying engines.
Python doesn’t have the concept of interface/trait, but all HyperBinary derived types share a common set of methods.
v.model() # Model enum
v.width()
v.cardinality()
v.stable_hash() # unique hash for this vector
v.seed128()
v.exponent() # (numerator, denominator), in lowest terms
v.hint() # HINT_* constant — the type this vector serializes as
hint(): the type on the wire
hint() reports which concrete type a vector serializes as, as one of the
hv.HINT_* constants:
| Constant | Type |
|---|---|
HINT_SPARSE_SEGMENTED | SparseSegmented 🍡 |
HINT_SPARKLE | Sparkle ✨ |
HINT_LEARNER | Learner 💫 |
HINT_SET | Set 🫧 |
HINT_SEQUENCE | Sequence 📿 |
HINT_OCTOPUS | Octopus 🐙 |
HINT_KNOT | Knot 🪢 |
HINT_PARCEL | Parcel 🎁 |
HINT_DART | Dart 🎯 |
HINT_POINT | Point 📍 |
HINT_CYCLONE | Cyclone 🌀 |
It is the tag hv.from_message dispatches on, so it also names the type a
round-trip gives back — which is why it reads the wire form rather than the
Python class:
s = hv.Set(seed, a, b)
s.hint() # HINT_SET
hv.from_message(hv.to_message(s)).hint() == s.hint() # True
s.power(0).hint() # HINT_SPARSE_SEGMENTED — see below
An identity vector has one canonical wire form, SparseSegmented with no
offsets, whatever type produced it. So hint() reports
HINT_SPARSE_SEGMENTED for any identity — matching what serialization
actually writes, and what a round-trip hands back.
Learner is the exception: an age-0 Learner still serializes its own payload,
because the RNG state has to survive. It reports HINT_LEARNER at every age.
Lazy materialization
Every type except SparseSegmented is defined by a recipe — much more compact than raw offsets.
The raw offsets will be computed and cached on first usage by APIs such as
core(), stable_hash(), overlap and similarity, serialization of SparseSegmented, etc. Other API calls, such as model(), domain(), pod(), exponent(), never materialize anything.
This is invisible to callers: the vector holds the same semantic content whenever you ask, but it means constructing vectors you never observe is nearly free, which is the typical and common use case for hypervectors.
compact() releases the cached content again, recursively through members. The recipe is retained, so the next observation recomputes exactly the same bits.
core() is the explicit crossing from recipe to bits: it computes the offsets
with any exponent folded in, and hands back a SparseSegmented reporting
exponent() == (1, 1). That holds for every type. See
SparseSegmented.
The tale of two equalities
Two levels are available, differing only in how hard they work:
equal_lazycompares recipes (and already-known content hashes), so it never materializes anything. It is conservative: aTrueanswer is always correct, while aFalseanswer may mean “not provable this cheaply” — two vectors of different concrete types, for example, or a coincidence that only the actual offsets would reveal.equalstarts with the lazy check and falls back to comparing content hashes, materializing if it must. Use it when the answer must be exact.
Concrete Types
| Type | Description |
|---|---|
| SparseSegmented 🍡 | Foundational vector — packed per-segment offsets |
| Sparkle ✨ | Seeded, deterministic hypervector |
| Learner 💫 | Online Hebbian learning |
| Set 🫧 | Unordered collection |
| Sequence 📿 | Ordered collection with positional encoding |
| Octopus 🐙 | Key-value composite |
| Knot 🪢 | Results from bind operator |
| Parcel 🎁 | Results from bundle operator |
| Dart 🎯 | Directed pair (tail → head) |
SparseSegmented 🍡
The most foundational vector type — a sparse binary hypervector where each segment has exactly one ON bit at the recorded offset location. All other types (Sparkle, Set, Sequence, etc.) ultimately contain a SparseSegmented in memory for processing, whenever necessary.
Structure
| Field | Description |
|---|---|
model | Sparsity configuration (Model) |
offsets | Packed bit array of per-segment ON offsets. nil/None = identity vector |
hash | Lazy-computed stable hash for equality checks |
domain / pod | The identifier for these offsets; serialized, so it survives a round trip |
exponent | The accumulated power, 1 if unpowered. See below |
The offsets are bit-packed according to the model’s sparsity bits — they do not align to byte boundaries. This trades a small CPU cost for compact, uniform storage that works both in memory and on disk.
Identity vector: when offsets is blank (zero storage), the vector is the identity vector where all offsets are 0.
Constructors
# Identity
ss = hv.SparseSegmented.identity(model)
Key Methods
ss.is_identity() # True if identity vector
ss2 = ss.power(2)
inv = ss.power(-1)
half = ss.power(1, 2) # fractional: ss^(1/2)
# Similarity
hv.overlap(a, b) # Count of matching ON bits
hv.hamming(a, b) # Count of differing segments
ss.offsets() # returns all offsets
ss.on(idx) # True if global bit index is ON
ss.offset(seg) # the ON offset within one segment
Bulk export to numpy
offsets() builds one Python int per segment, which is the wrong shape for
an array library. hv.code_to_np() hands back the same offsets as a numpy
array, and hv.codes_to_np does a whole batch in one call — about 27x
faster than iterating, and close to a memory copy.
a = hv.code_to_np(v0) # (M,), uint8 or <u2
# One call for a whole codebook: row i is vectors[i].
codes = hv.codes_to_np([v0, v1, v2]) # (3, M)
# And back. An array carries no identity, so (domain, pod) come from you.
ss = hv.code_from_np(model, domain, pod, a)
vs = hv.codes_from_np(model, domain, pod, codes)
The dtype is uint8 at 8-bit and <u2 for every wider model — one element per
segment, since every model’s offset fits 16 bits. The export is zero-copy,
reading over immutable bytes; an offset wider than the segment is masked into
it on the way back, as every write path does.
The byte order is fixed little-endian, not the host’s, so the same vector exports to the same bytes everywhere.
Offsets are ring angles, so lift before you compute
An exported offset is an angle on the segment’s ring, not a coordinate. Euclidean array math on it is meaningless, and silently so: two vectors each exactly one ring step from a base read distances of 32.0 and 32736.0 at 10-bit, for the identical true relation, because one of them wraps. Nothing in numpy or torch will stop you.
hv.phasor_table(model) is the lift. It returns the ring’s
segment_size(model) unit phasors as complex64, so turning offsets into
something you can do linear algebra on is a gather:
O = hv.codes_to_np(vectors) # (n, M) ring offsets
Z = hv.phasor_table(model)[O] # (n, M) complex64 — one gather
# All-pairs similarity is then one matmul, and it IS hv.alignment.
S = (Z @ Z.conj().T).real / hv.cardinality(model)
# For torch layers that reject complex dtypes: (W, 2) float32 instead.
table = hv.phasor_table(model, real=True)
Measured 10x faster than exp(2j*pi*O/W) per element at (512, 1024), and
bit-identical — the table holds every value that exponential can take, so there
is nothing to approximate. The matmul reproduces hv.alignment to better than
1e-5. The table itself is built once per model inside the library and handed out
zero-copy.
complex64 is the compute dtype: torch accepts it with no conversion. The raw
offsets are uint16, which torch will convert to a tensor and then refuse to do
arithmetic on — but that only matters if you meant to do the algebra there.
Bind, release and power belong in kongming; the array boundary is for the
numbers a network consumes, and those want the lift.
The export copies, so the array freezes the content at the moment of the call.
For an immutable vector that never matters. For a Learner it does:
bundling after an export does not reach the array you already hold, and nothing
warns you — re-export after every change you need reflected.
A view is not an option. The offsets are bit-packed below 16-bit, the buffer mutates and can move underneath an alias, and an identity vector holds no buffer at all.
Composites are accepted and materialized to their core first, so they
contribute only their offsets: a Point’s coordinates and frame, or a
Learner’s weight distribution, do not survive the trip.
Chained powers are exact
power() reports the exponent you asked for, and core() folds it into the
offsets:
ss = hv.Sparkle.from_word(model, "pos", "step").core()
ss.exponent() # (1, 1) — unpowered
ss.power(3).exponent() # (3, 1)
ss.power(3).core().exponent() # (1, 1) — core() folds it in
Chaining composes on the rational, so a chain of powers agrees exactly with the single equivalent power — scaling truncates only once however long the chain:
hv.equal(ss.power(5, 4).power(7, 3), ss.power(35, 12)) # True
hv.equal(ss.power(1, 2).power(2, 1), ss) # True
That matters for EXPANDING exponents, which is what
fractional-power encoding uses: scaling step by step instead would
disagree as soon as an intermediate wraps past the ring — measured 70 Lee steps
apart for 5/4 then 7/3 at 10-bit. Contracting chains agree either way,
since floor(floor(x/a)/b) really is floor(x/(a*b)) and nothing wraps on the
way down.
A powered vector survives the wire with that exactness intact, and domain and pod are written too — they identify the offsets rather than transform them.
core() returns eagerly-applied offsets
core() on any type crosses from recipe to materialized, which means it
computes the offsets and folds in every pending exponent:
half = hv.Set(seed, a, b).power(1, 2)
half.exponent() # (1, 2) — the composite still describes itself
half.core().exponent() # (1, 1) — the returned offsets already include the 1/2
So core() is the boundary where a lazy vector becomes concrete bits. Reading
it forces the computation, and the result is self-contained: no exponent left to
apply, nothing further to resolve.
Scaling truncates toward zero, so once a fractional power is applied the
scaled offsets have lost that information for good. What the retained base buys
is that the loss is never compounded: a chain re-scales from the base, so
ss.power(1, 2).power(2, 1) does recover ss exactly, and a three-deep
chain truncates no more than a one-step one.
A lazy Sparkle reaches the same place by a different route — the exponents
cancel in the recipe before anything is computed. See
Sparkle.
Sparkle ✨
Sparkles are the atomic building block for higher-level constructs. Domain is a logical namespace that groups related Sparkle instances. Pod acts as the secondary identifier for a Sparkle instance.
Sparkle is deterministic: the same (domain, pod) pair always produces the same offsets, across all sessions and engines. For this reason, the (model, domain, pod) triple uniquely identifies a Sparkle, and we store the triple rather than the raw offsets for huge space saving.
Sparkle Constructors
# From a word string
s0 = hv.Sparkle.from_word(model, "animals", "cat")
# From a numeric seed
s1 = hv.Sparkle.from_seed(model, "animals", 42)
# From a prewired enum
s2 = hv.Sparkle.from_prewired(model, "animals", hv.PREWIRED_SET_MARKER)
# Identity vector
s3 = hv.Sparkle.identity(model)
# Random (from SparseOperation)
so = hv.SparseOperation(hv.MODEL_10BIT, 0, 42)
s4 = hv.Sparkle.random("animals", so)
# From domain + pod directly — primary constructor
s5 = hv.Sparkle(model, "animals", pod)
Key Methods
s0.model() # Model enum
s0.stable_hash() # Deterministic and unique hash
s0.exponent() # Current exponent, as (numerator, denominator): (1, 1) for a base vector
s0_square=s0.power(2) # Returns p-th power (new Sparkle)
hv.equal(s0, s0_square) # s0_square = s0^2, different from original s0.
s0_half=s0.power(1, 2) # Fractional power: s0^(1/2)
s0_half=s0.power(1, denominator_ls=1) # Same as above, denominator as 2**ls
core0=s0.core() # Returns underlying SparseSegmented
core0.offsets() # The raw offsets for each segment.
power(0) returns the identity vector, which every type supports: the result
keeps its concrete type but holds identity’s content, so it serializes in the
canonical SparseSegmented nil-offsets form and reports
hint() HINT_SPARSE_SEGMENTED.
power(-1) returns the inverse.
Fractional powers
power() takes an optional denominator, so the exponent can be fractional instead of an whole integer. Each offset is scaled by numerator / denominator and
truncated toward zero, which places s^(1/2) “half way” along the permutation
that power(1) walks in one step.
s = hv.Sparkle.from_word(model, "pos", "step")
s.power(1, 2).exponent() # (1, 2)
s.power(-3, 4).exponent() # (-3, 4) — the sign always rides on the numerator
s.power(6, 2).exponent() # (3, 1) — reduced to lowest terms, so this is the
# integer power, and takes the integer path
# A fractional power is near-orthogonal to the base AND to the integer powers.
hv.overlap(s, s.power(1, 2)) # ≈ 0
hv.overlap(s.power(1, 2), s.power(2)) # ≈ 0
print(s.power(1, 2)) # ✨:🔗pos,🌱step,💪1/2
print(s.power(-3, 4)) # ✨:🔗pos,🌱step,💪-3/4
The exponent is always kept in lowest terms with the sign on the numerator, so
power(6, 2) and power(3) are the same vector, and exponent() never reports
an unreduced pair.
denominator_ls: the denominator as a shift
power() also accepts denominator_ls, which spells the denominator as
2 ** denominator_ls. It is consulted first; denominator applies only when
denominator_ls is unspecified. So power(1, denominator_ls=3) is exactly power(1, 8).
The two forms produce identical results, but the power-of-two computation can be cheaper, as the scaling runs on an integer path. On the wire it encodes as a small shift rather than a full integer as well.
Scaling truncates toward zero, so a fractional power discards information that a later power cannot restore. What both forms guarantee is that the loss is never compounded:
s = hv.Sparkle.from_word(model, "pos", "step") # lazy
ss = s.core() # materialized
hv.equal(s, s.power(1, 2).power(2, 1)) # True
hv.equal(ss, ss.power(1, 2).power(2, 1)) # True
Both hold because chaining composes the exponents and scales once, rather than scaling at each step. See chained powers are exact.
Note that core() is the materialization step: it computes the offsets with
every exponent folded in, so what it returns reports exponent() == (1, 1).
Pretty-printing
# Pretty-printing, or s.__str__()
print(s0)
# ✨:🔗animals,🌱cat
# More detailed information, or s.__repr__()
s
# hint: SPARKLE
# model: MODEL_10BIT
# stable_hash: 9725717137035622833
# domain:
# name: animals
# pod:
# word: cat
During pretty-printing of Sparkle instances, you may notice special emoji for domain / pods.
| Emoji | Variant | Example |
|---|---|---|
| 🔗 | named domain | 🔗animals, 🔗PREFIX.name |
| 🌐 | numeric domain | 🌐0x..c862 |
| 🌱 | named pod | 🌱cat |
| 🫛 | numeric pod | 🫛0x..80e4 |
| 🍀 | pre-defined pod | 🍀SET_MARKER |
| 💪 | Exponent / Power | 💪3, 💪-1, 💪1/2, 💪-3/4 |
Identity vectors display as IDENT (e.g., ✨IDENT).
The underlying offsets are lazily generated from a seeded PRNG. Only the seeds are stored in serialization, which is a significant storage saving.
Learner 💫
Learners are designed to perform online bundling for a stream of observations, in the form of Hebbian learning.
The representational budget is fixed, in the form of segment count from a single hypervector: what matters is the distribution of weights among observed vectors.
Constructors
learner = hv.Learner(model, hv.Seed128(0, 42))
# age-1 learner that starts having seen `obs`.
learner = hv.Learner(model, hv.Seed128(0, 42), initial=obs)
# optional keyword-only rng_hint pins the RNG backend (default: process-wide).
learner = hv.Learner(model, hv.Seed128(0, 42), rng_hint=hv.RNG_PHILOX_4X64)
# a randomly-initialized learner.
learner = hv.Learner.random(so)
Feeding Observations
learner.bundle(a) # single observation
learner.bundle_multiple(b, 3) # three whole observations
# Below one observation. Weights are numerators over hv.mass_denominator(model),
# so a quarter-observation is that denominator // 4.
learner.bundle_fractional(c, hv.mass_denominator(model) // 4)
Inspection
learner.age() # how many bundle calls, whatever weight they carried
learner.total_mass_units() # the learner's whole accumulated weight, in units
learner.blank() # bool: whether this learner is blank (nothing observed yet)
learner.model() # identity accessors: model / domain / pod
learner.domain()
learner.pod()
learner.support(a) # overlap above the chance baseline, clamped at 0
learner.occupancy(a) # a's share of the accumulated weight; unbiased, so
# it reads negative below chance (clamp at the call
# site if you need a non-negative share)
learner.mass_units(a) # a's accumulated weight, in the same units;
# mass_denominator(model) of them is one observation
hv.mass(learner, a) # ... the same, converted to whole observations
# (a float: 0.4 reads 0.4, not 0)
Support and Occupancy require content to probe against: calling either on a
blank learner is a contract violation and panics (a
PanicException in Python); check blank() first.
Deferred Observations
A young Learner does not need to build its raw buffer immediately: instead it defers the observations themselves as a small list of (vector, weight) pairs, and only materializes the buffer once keeping the list no longer pays. A deferred observation is a recipe, typically far smaller than a full offsets buffer, so young learners cost a fraction of a materialized buffer, in memory and on the wire.
This also implies:
- Repeats are free. Bundling a pattern the learner already holds bumps that entry’s weight when the recipes match lazily (
EqualLazy); a repeat arriving in a different representation may land as a fresh entry. A learner that sees the same pattern a thousand times still holds one entry, and never materializes at all.
learner.has_deferred_data() # True while observations are still deferred
for entry in learner.deferred_data():
print(entry) # the deferred observations, in arrival order
learner.compact() # drop incidental materializations (content unchanged)
Whether a learner is still deferring observations or has already materialized its buffer changes nothing observable. The distinction is purely internal: refer to lazy materialization.
See also
- Learner concepts — the fixed budget, diversity vs. repetition.
- LearnerPool — pooled Learners behind address-keyed access circles.
LearnerPool 🎱
A LearnerPool is an aggregate over member Learners for improved scalability: a fixed roster of members that collectively serves many address-keyed learning tasks in parallel. Writes to an address land on a small access circle of members; heavy addresses recruit more members as needed while light addresses keep a nearly-private one. See the concepts chapter for why and how.
Constructors
# model, member domain, roster size
pool = hv.LearnerPool(hv.MODEL_8BIT, "pool", 65536)
pool.init() # fill the still-empty roster with fresh Learners
Writing
bundle stores data under addr. Omitting the address stores the pattern
auto-associatively.
pool.bundle(data, addr=addr) # hetero-associative write
pool.bundle(data, addr=addr, multiple=3) # three whole observations
# Below one observation: a numerator over hv.mass_denominator(model).
pool.bundle_fractional(data, addr, hv.mass_denominator(model) // 4)
When reaching the collective capacity of the pool, it refuses future write.
Reading
We support wwo read scenarios:
support— evidence thatprobewas stored underaddr(a scalar, noise-subtracted). This is the discriminative read: “how strongly does the pool associate addr → probe?”read_members— the content/experiences of the circle’s members, one hypervector each. This is the generative read: use them as attractors for near-neighbor search when you don’t know theprobein advance.
s = pool.support(addr, probe) # scalar evidence
m = pool.mass(addr, probe) # probe's accumulated weight, whole observations
for attractor in pool.read_members(addr):
... # feed into NNS / overlap checks
Introspection
pool.total() # fixed member count
pool.load() # total write mass W = Σ member ages
pool.unique_estimated() # ≈ distinct items held in this pool
pool.member_domain() # the members' domain
Persistence
A pool serializes as a small self-describing sentinel — its metadata as a LearnerPoolProto — plus one ordinary chunk per trained member.
The pool serializes as metadata plus per-member contents. Round-trip via the memory layer: the pool sentinel is self-describing, so loading needs no config.
# load from a substrate view in one call.
pool = memory.load_learner_pool(view, member_domain)
# or manually: metadata first, members via a loader callback
pool = hv.LearnerPool.from_proto_bytes(raw)
pool.hydrate(lambda domain, pod: ...) # return Learner or None (blank)
See also
- LearnerPool concepts — why a pool, access circles, diversity vs. repetition.
- Learner — the member primitive.
Set 🫧
An unordered collection of hypervectors. See Composites: Set for the conceptual overview.
Constructor
s = hv.Set(hv.Seed128(0, 42), first, second, third)
Notable methods
# All these will be approximately 1/3 of the total cardinality.
hv.overlap(s.unmasked(), first)
hv.overlap(s.unmasked(), second)
hv.overlap(s.unmasked(), third)
Sequence 📿
An ordered collection of hypervectors with positional encoding. See Composites: Sequence for the conceptual overview.
Constructor
# Constructing a sequence, with logical index start at 1 (default to 0).
seq = hv.Sequence(hv.Seed128(0, 42), first, second, third, start=1)
Derived Sequences: Append / Prepend / Reset
Append, Prepend, and Reset all return a new Sequence — a
Sequence is an immutable value, so the receiver is never changed.
Append(more...)— members added at the end.startis unchanged.Prepend(more...)— members added at the front;startdecrements bylen(more)so existing members keep their positional binding.Reset(start)— shift the starting index. Returns an equal Sequence whenstartequals the current start.
The result equals what you’d get by building a fresh
NewSequence(seed, new_start, all_members...) — the domain/pod seed is
preserved.
seq = hv.Sequence(hv.Seed128(0, 42), a, b, c)
# Append / Prepend are variadic and return new Sequences.
s1 = seq.append(d, e) # [a, b, c, d, e]; seq unchanged
s2 = seq.prepend(x, y) # [x, y, a, b, c], start -= 2; seq unchanged
s3 = seq.reset(10) # starting index 10; seq unchanged
Octopus 🐙
A key-value composite where each value is bound with its key’s Sparkle. See Composites: Octopus for the conceptual overview.
Constructor
Keys are Pods. In Python, strings (and any value polymorphically convertible to Pod) are accepted and auto-converted.
oct = hv.Octopus(hv.Seed128(0, 42), ["color", "shape"], red, circle)
Key Methods
oct.value_by_key("color") # accepts Pod | str | int | Prewired
Knot 🪢
Knot 🪢 contains the result of binding (multiplicative composition) of hypervectors, while tracking its member parts for serialization and introspection. See Composites: Knot.
Constructor
# More commonly via the bind operator:
k = hv.bind(a, b)
Extending a Knot
An existing Knot can be extended with additional parts via
expand. This returns a new
Knot (as a Knot is an immutable value) — equivalent to re-binding all
parts from scratch but without reconstructing the base.
k = hv.bind(a, b)
k2 = k.expand(c) # k2 is equivalent to hv.bind(a, b, c); k is unchanged
Parcel 🎁
Parcel 🎁 contains the result of bundling (additive composition) of hypervectors, while tracking its members and bundling seed for serialization and debugging. See Composites: Parcel.
Constructors
# Direct, with optional per-member weights:
p = hv.Parcel(hv.Seed128(10, 1), a, b, c, weights=[0.6, 0.2, 0.2])
Key Methods
p.count() # member count
p.members() # the tracked members
Dart 🎯
A one-directional reference between two hypervectors. A Dart is “thrown” from a tail to a head:
See Composites: Dart.
Constructor
# Or via the release operator (note the order: release(head, tail)):
p = hv.release(head, tail)
Endpoints
A Dart retains references to its endpoints.
p.tail() # thrown from ...
p.head() # ... to
Recovering endpoints
p = hv.release(h, t) # the Dart thrown t → h
recovered_h = hv.bind(p, t) # ≈ h
recovered_t = hv.bind(p.power(-1), h) # ≈ t
Anti-commutativity
Dart (and the release operator that constructs it) is anti-commutative:
Point 📍
A position in the space a frame of basis vectors spans. Given bases , coordinates , and an anchor :
The coordinates are exponents, so a Point is the fractional-power encoding of an -tuple on one shared frame. Two Points on the same frame are comparable; the same offsets under a different frame mean a different position.
The anchor is the Point’s own identity, supplied by the caller and unrelated
to the frame’s. It keeps the origin off the identity vector: without it every
frame shares one origin, Point(0, …, 0) is the all-zero-offset vector — the
single cell not drawn like the others — and unrelated frames collide there.
Anchored, the origin is just another sparkle, and distinct anchors separate
distinct frames.
domain and pod are new leading arguments on Point and on all three
recover_point* functions, and the anchor changes every Point’s content —
Points stored before the anchor decode to different vectors.
Separately, fractional coordinates moved to Point.fractional, coords became
required, and short coordinate lists no longer pad with the origin. See the
changelog for the release
this landed in.
Why the coordinates are kept
A Point carries its coordinates rather than folding them into the vector, because bind is not exactly additive on these codes due to roundoff errors:
The two disagree on about half the segments, because loses 1 against . So coordinate arithmetic has to happen on the rationals and truncate once, at materialization. A Point keeps one coordinate per axis and can do that.
Constructors
frame = [hv.Sparkle(model, d, hv.Pod("b0")), hv.Sparkle(model, d, hv.Pod("b1"))]
anchor_d, anchor_p = hv.Domain("grid"), hv.Pod("origin")
p = hv.Point(anchor_d, anchor_p, frame, [5, 9]) # integer coordinates
# Fractional: ONE denominator for every axis, a positive power of two.
p = hv.Point.fractional(anchor_d, anchor_p, frame, [4100, 4096], 4096)
# The origin is spelled 0 on every axis.
p = hv.Point(anchor_d, anchor_p, frame, [0, 0])
# The STORAGE shape, below.
p = hv.Point(anchor_d, anchor_p, frame, [5, 9], keep_frame=False)
The frame must share a model and be pairwise distinct and non-identity.
One coordinate per axis, always. Both constructors raise when the count
disagrees with the frame; there is no padding, because filling in a forgotten
axis with the origin is a silent wrong answer rather than a convenience. The
integer form takes plain ints and rejects a (numerator, denominator) pair —
a grid is one shared step, which is the only case fractional-power encoding
uses, so the denominator belongs to the call and not to each axis.
Inspection
p.rank() # axis count — len(coords), whether or not the frame is held
p.coords() # [(numerator, denominator), ...] in lowest terms
p.frame() # the basis vectors, empty when not retained
p.is_ready() # bool: whether the frame is held
The storage shape: a Point without its frame
Many Points usually share one frame, and storing a copy per record is waste.
keep_frame=False keeps the coordinates and drops the frame:
stored = hv.Point(anchor_d, anchor_p, frame, [5, 9], keep_frame=False)
stored.is_ready() # False
stored.rank() # 2 — the coordinates are still there
live = stored.attach_frame(frame) # a NEW Point; Points are immutable
live.is_ready() # True
stored = live.detach_frame() # the same thing from an existing Point
The frame argument is still required and validated when keep_frame=False
— it supplies the model and the axis count to pad to — it is simply not
retained.
It cannot check what you hand it. The anchor is the Point’s own domain/pod, so
it fingerprints nothing about the bases, and attaching the wrong frame
silently reads a different position rather than raising. Only the axis count is
verified. If that matters, materialize and confirm with recover_point.
A non-ready Point’s content reads as the bare anchor, not the position: it
is for writing, not computing. Use is_ready() to tell the two apart — a
genuine origin Point reads as the anchor too, so content alone cannot.
Recovering coordinates from raw offsets
Given a frame and a bare SparseSegmented, the coordinates can be solved for.
Three functions, in increasing cost and tolerance:
# The anchor must match the one the vector was built with: it is RELEASED from
# raw before the solve, and a wrong anchor leaves noise the solver rejects.
hv.recover_point(anchor_d, anchor_p, frame, raw) # exact solve
hv.recover_point_fractional(anchor_d, anchor_p, frame, raw, 12) # 1 / 2**12 grid
# Integer, tolerating up to max_bad corrupted segments. Returns the Point AND
# how many segments disagreed; max_bad=0 is exactly recover_point.
point, bad = hv.recover_point_noisy(anchor_d, anchor_p, frame, raw, 8)
| method | tolerates corruption | practical rank | |
|---|---|---|---|
recover_point | exact modular solve | no | any |
recover_point_fractional | lattice reduction (LLL + Babai), then polish | no | 10-bit and up: through 10; 8-bit: about 4 |
recover_point_noisy | consensus over random segment subsets (RANSAC) | yes, up to max_bad | tolerance falls with rank — see below |
The fractional grid has a floor. A power truncates, so a coordinate delta below moves no segment at all. Inside that plateau the position is genuinely indistinguishable from the origin — the information is not in the vector, so no solver recovers it. At level 12 and that is a delta under 4.
Noise tolerance costs rank. A random subset of segments is usable only when its pivot rows are all clean, which has probability — so the corruption a solve survives shrinks as the rank grows. Measured, exact recovery holds to roughly 59% corrupted segments at rank 3, 39% at rank 5 and 20% at rank 10.
recover_point cannot tolerate even one bad segment: the coordinates live in a
modular group with no notion of “close”, so a single wrong offset among the ones
the solve pivots on randomizes the answer outright. A vector that is not on the
frame at all still raises, rather than passing as heavily corrupted.
Resolving a Point is NOT a resonator network. That was measured and does not work here: the cleanup scores an exact-offset match, so a wrong power sits at chance with no slope toward the right answer. A resonator needs the score to degrade smoothly as it approaches the solution, and it also discards the very structure that makes the solve possible — FPE offsets are , linear in the exponent.
Comparing Points
A Point is the type where Lee distance earns its keep. Because the offsets are fractional powers, they carry an ordinal meaning: nearby positions have nearby offsets, and Lee reads that gradation where overlap only reports agreement and collapses into noise as positions separate.
The gradation has the same floor as recovery, though — a coordinate delta inside the plateau reads Lee 0, because no segment moved.
The anchor does not disturb any of this. Bind is an isometry, so binding the same anchor into both sides shifts them together: Lee and overlap between two Points sharing an anchor are exactly what they were without one. What the anchor changes is comparison against the identity — and against a Point on a different anchor, which now reads as unrelated rather than as the same position.
Hazards
Both inherited from fractional-power encoding, and both easy to trip:
-
Keep fractional exponents at or above 1. Below 1 the encoding degenerates, for an exact reason: contracts every offset into , so two different base vectors stop being orthogonal — they are both crushed into the same narrow band. At the limit measures as the identity outright.
So distinct codes raised to the same small power retain spurious overlap (one measured pair: 18 segments at and 8 at , against near-chance once — single draws, so read the trend and not the counts).
The fix is in how you encode: put a continuous value on a grid as the numerator over . That keeps in , where cross-vector orthogonality is clean. Nothing enforces this — it is the caller’s to get right.
-
Bind is not additive on fractional powers — the reason the coordinates are kept at all. Do arithmetic on
coords(), build a new Point, and let it truncate once.coords()hands back per-axis pairs in lowest terms, so rebuilding throughPoint.fractionalmeans putting them over a common power-of-two denominator first. -
The anchor is part of the position. Reuse the same
(domain, pod)for every Point you intend to compare or recover. A different anchor is a different vector, so two Points at identical coordinates on identical frames do not match, andrecover_pointraises rather than returning the wrong answer — it releases the anchor you pass before solving, and a wrong one leaves noise that fails the all-segments check. Store the anchor alongside the frame.
See also
- Utilities —
lee_distance, the graded read. - Operators —
power, and what fractional exponents mean. - HyperPhaser 🧭 — the accumulator, and the other place offsets are read as ordinal rather than as labels.
Cyclone 🌀
A periodic hypervector: raising it to its own period gives back the identity.
That makes it the natural carrier for anything cyclic — a phase of the day, a position within a repeating window, a step in a loop — where you want position and position to be the same vector rather than merely similar.
How it works
power scales every offset, and a Cyclone is built so that every offset is a
multiple of
for segment size . Raising to the period therefore sends each offset to a
multiple of , which is on the ring — the identity, exactly and for every
segment at once.
This is also why the period must divide the segment size: otherwise no such
exists and the constructor refuses with impossible periodic vector.
Constructors
# W = 1024 for the 10-bit model, so the period must divide 1024.
c = hv.Cyclone(model, hv.Seed128(hv.Domain("clock"), hv.Pod("hour")), 64)
c.period() # 64
hv.Cyclone(model, seed, 100) # ValueError: impossible periodic vector
The defining property
hv.is_identity(c.power(64, 1)) # True — a full turn
hv.is_identity(c.power(32, 1)) # False — half a turn is not
Powers below the period are distinct vectors, so c.power(k, 1) enumerates
period positions around the cycle before returning to where it started.
Seeded versus default
The seed decides the shape, not the period:
# A real seed: offsets are random multiples of b.
c = hv.Cyclone(model, hv.Seed128(hv.Domain("clock"), hv.Pod("hour")), 64)
# The default (zero) seed: a characteristic SAWTOOTH, offset = b * segment.
c = hv.Cyclone(model, hv.Seed128(hv.d0(), hv.p0()), 64)
list(c.core().offsets())[:6] # [0, 16, 32, 48, 64, 80]
Use a real seed for anything you want orthogonal to other cyclones. The sawtooth is deterministic and shared by every default-seeded Cyclone of the same model and period, which makes it useful for tests and visualization and unsuitable as a distinct identity.
See also
- Operators —
power, which is what the periodicity rests on. - Sequence 📿 — for ordered, non-repeating structure.
Operators
See Concepts: Operators for the full overview.
Bind
bound = hv.bind(a, b)
released = hv.release(bound, b) # this will recover `a`
hv.equal(a, b) # hash equality
Release
Extracts one component from a binding:
bound = hv.bind(role, filler)
recovered = hv.release(bound, role) # Dart; ≈ filler at the bit level
Expand (extend a Knot)
Extends an existing Knot with additional operands without
re-binding from scratch. k.expand(c) on k = bind(a, b) returns a
new Knot equal to bind(a, b, c) — a Knot is an immutable value, so
k itself never changes.
k = hv.bind(a, b)
k2 = k.expand(c) # k2 is equivalent to hv.bind(a, b, c); k unchanged
Bundle
p = hv.bundle(hv.Seed128(10, 1), a, b, c)
HyperPhaser 🧭
A second way to bundle a stream of observations. A Learner 💫 reads each offset as a label and compares by overlap; a phasor bundle reads it as a phase and compares by Lee distance or alignment.
Recall from concepts that a SparseSegmented
vector is already a list of phasors — the ON bit’s offset within its segment is
a discretized phase. A HyperPhaser takes that literally: it superposes unit
phasors and keeps the resulting angle, which is FHRR’s bundle operator living
inside kongming’s existing representation.
So there is no separate “phasor vector” type: every hypervector already is
one. What a HyperPhaser adds is the accumulator — the one form that is NOT a
hypervector:
HyperPhaser | any HyperBinary | |
|---|---|---|
| state | dense complex, components | one offset per segment |
is a HyperBinary? | no — no wire form | yes |
| role | accumulate | compare, store |
| magnitudes | kept, per segment | dropped — angle only |
HyperPhaser.quantize() crosses from the accumulator to a
SparseSegmented 🎞️, one way — the name says the cost: it
rounds each phase to the ring and drops the magnitudes.
What it estimates
Comparing two phasor bundles estimates the cosine between the underlying weight vectors:
with standard error — it is a random projection, whose basis is the codebook you feed it. That single fact sets expectations: the readout is scale-free (re-presenting the same data changes nothing but magnitude), flat in the number of distinct observations, and sharper at larger because buys ranking resolution rather than fidelity.
Accumulating
ph = hv.HyperPhaser(model, hv.d0(), hv.p0())
ph.bundle(a, 1.0) # one whole observation
# Any signed float: 1.0 is one whole observation, so a quarter is 0.25.
ph.bundle(b, 0.25)
# NEGATIVE SUBTRACTS, which is what makes match-and-subtract work in place.
ph.bundle(b, -0.25)
ph.dimension() # how many phasors: one per segment
ph.mass() # total weight bundled: 1.25 after the three above
ph.magnitude_squared() # 0.0 iff nothing is accumulated
ph.copy() # deep copy; the accumulator IS the storage
Unlike a Learner’s, these writes are deterministic and linear. No RNG is drawn, so:
- order never matters — the same observations in any order give the same bytes, where reservoir sampling gives an order-dependent realization;
- duplicates are harmless — bundling something twice equals bundling it once at double weight, which only rescales and leaves every angle fixed;
- shares below survive — a Learner is a sample, so a member owning less than one segment is invisible; a phasor accumulates, so small weights still move every segment.
The cost is resumability. A Learner resumes from its offsets plus one age scalar; a phasor needs all magnitudes, because accumulated mass is per-segment.
There is no call count — nothing on the write path consults one, and
magnitude_squared() == 0 already answers “has anything been accumulated”.
There is an accumulated-weight total, mass(), and it is state rather than
bookkeeping: does not recover it. That
quantity estimates , which is
when the observations are mutually unrelated and when
they agree — so the magnitudes fix neither the weight nor the agreement
on their own. mass() supplies , and coherence() then solves for
.
A counter would also have been the wrong emptiness test. A blank accumulator simply is zero in every segment, so
magnitude_squared() == 0is the whole question — and unlike a call count it stays honest for an accumulator that was bundled and then subtracted back to exactly zero.
Merging two accumulators
merge() adds another accumulator in, segment by segment, masses included:
# Two shards trained apart, combined into the state one would have reached.
left.merge(right) # z_i += w_i; mass() adds
That is the whole point: vector addition of two resultants is the maximum-
likelihood fusion of the two estimates, so sharded training combines exactly
rather than approximately. It is exact to float rounding — addition does not
associate, so the two groupings sum in different orders — and bit-exact where
the grouping does line up, a one-observation operand contributing the very
product bundle() would add.
bundle() cannot stand in for it. Its operand is a hypervector, so folding an
accumulator in that way means quantize()ing it first, which gives every
segment the same weight and discards what each one actually knew: measured,
correlates 0.717 against the true sum, and at weight 1.0 it silently
drops 31 of 32 observations. Identity stays the receiver’s, as under bind().
Reading the accumulator
ph.angle(seg) # accumulated phase in radians, [0, 2*pi)
ph.magnitude_at(seg) # resultant length r_i, one segment
ph.magnitude_squared() # the whole vector: sum_i |z_i|**2
ph.coherence() # rho in [0, 1]: the share of mass that agrees
magnitude_at() is a per-segment confidence, not a length. Within one vector
it varies by roughly 8x, and it says how much the contributing phases cancelled
there — a near-zero resultant means the stored angle is decided by rounding
residuals and carries no information. A segment with a large resultant also
resists new observations, which makes it per-segment plasticity where a Learner
has only a scalar age.
A cancelled segment reports angle 0.0, which is indistinguishable from a
genuine zero phase: read magnitude_at() to tell them apart.
magnitude_squared() is the whole-vector reading, and it is squared rather
than a norm on purpose: that is the moment with an exact law,
at weight and coherence , so the sum estimates times it. The norm
itself carries a per-segment Rayleigh factor (0.886) that the second moment does
not, which is why rms derives from here rather than from averaging
magnitude_at().
It is not a stand-in for the mass. The law is linear in only for
mutually unrelated observations and quadratic once they agree, which the two
exact values make plain: one unit observation gives magnitude_squared() == M,
and the same observation n times gives n**2 * M, not n * M.
Coherence: how much of the mass agrees
coherence() inverts that law for , the share of the accumulated mass
pointing one way:
It reads 1 when every observation wrote the same angle and 0 when the angles were unrelated. It is the parameter the magnitudes cannot give up alone, because unrelated observations and agreeing ones both read :
| content | mass() | mean | coherence() |
|---|---|---|---|
| 1024 unrelated words | 1024 | 27.3 | 0.00 |
| 32 identical observations | 32 | 32.0 | 1.00 |
| 40 observations, jittered | 40 | 33.6 | 0.84 |
All three look the same from magnitude_at(); is why. It
derives from the second moment rather than from averaging magnitude_at()
because the cross terms vanish there — the mean magnitude keeps a Rayleigh
floor and so never reads 0 on junk, as the 27.3 above shows.
A mass of 1.0 or less reads 1: one observation agrees with itself, and de-biasing is then a no-op.
Reading back what went in
alignment() scores a candidate against the accumulator and returns the weight it
was bundled at — not a similarity:
ph.bundle(cat); ph.bundle(cat); ph.bundle(dog)
ph.alignment(cat) # ~2.0 — bundled twice
ph.alignment(dog) # ~1.0 — bundled once
ph.alignment(fish) # ~0.0 — never bundled
Those readings assume the observations agreed. In general alignment()
returns — mass() times coherence()
— so 40 noisy observations of one thing at read 33.5, not 40.
Divide by coherence() to recover the count; that quotient is exact to ~0.1%
over and .
It works because the scoring rule gives partial credit. Compare the two:
| rule | |
|---|---|
| overlap | count the segments where the two offsets are equal |
alignment() | add up over the segments, then divide by |
Overlap is all-or-nothing per segment. alignment() scores two offsets one ring
step apart at , just under 1, where overlap scores them 0 —
and scores a half-turn at , which overlap cannot express at all.
That is also why the weight comes back. A member’s own phases line up, each contributing , so copies sum to ; every other member sits at an unrelated angle, and cosines of scattered angles average to zero. The estimate is unbiased, with the usual wobble from that cancellation being imperfect — so a non-member reads near 0, not exactly 0.
alignment() reads its argument as unit phasors, exactly as bundle() does, so a
quantized vector works too and costs only the magnitudes it dropped.
It scores; it does not search
alignment() needs you to name a candidate, which raises the obvious question: how
do you find one without trying the whole codebook? The answer is that the
search is ordinary near-neighbor search,
and it needs nothing new:
| the question | HyperBinary | HyperPhaser |
|---|---|---|
| how close are these two? | hv.overlap(a, b) | ph.alignment(c) |
| which stored vector is my probe? | NNS over the index | the same NNS |
| what is inside this bundle? | NNS over the index | no index — enumerate |
Row 2 is the one that surprises. A noisy probe is a corrupted code, not a
superposition, so most of its segments still carry exact offsets and the
overlap-keyed index finds it — measured correct at rank 1 through 95%
corrupted segments. So retrieval is two steps, neither of them a scan: let the
probe drive NNS over the codebook, then let alignment() say whether the
accumulator has actually seen the winner, and how often.
Row 3 is the real gap. A Learner’s offsets are member offsets — reservoir
sampling copies them, so exact matches survive and the index can see them. Every
offset in a phasor bundle is a vector sum, so no member’s offset survives
intact and the index is blind to it. Asking “what is in this bundle” with no
probe to narrow it therefore costs one alignment() per candidate.
Binding and releasing
bind() multiplies the accumulator segment by segment, and release() divides
back. The pair is what lets you put a key on a bundle and take it off again:
ph.bundle(cat, 2.0)
ph.bundle(dog, 1.0)
ph.bind(key) # every term now carries the key
ph.release(key) # and back: alignment() reads 2.0 and 1.0 again
It distributes over bundle(), which is the whole reason it is useful on an
accumulator: binding a sum binds every term in it. So the interesting direction
is the other one — release a key off a superposition and alignment() reads what
that key was bound to, without ever enumerating the bundle:
ph = hv.HyperPhaser(model, hv.d0(), hv.p0())
ph.bundle(hv.bind(role, filler), 1.0)
ph.release(role)
ph.alignment(filler) # ~1.0 — the filler, recovered
The operand picks the arithmetic
| operand | contributes | magnitudes |
|---|---|---|
a HyperPhaser | its exact phase and its magnitude | multiply |
any HyperBinary | a phase off the model’s ring, read as a unit phasor | untouched |
A hypervector operand is therefore a pure rotation: it moves the accumulator around the torus without changing how much evidence any segment carries. An accumulator operand is the full complex product, so a half-weight key halves the magnitudes it touches.
release() is a true inverse in both cases: it divides, computing
, so whatever magnitude bind()
multiplied in divides back out. Two consequences worth knowing:
- A segment whose operand is exactly zero stays zero.
bind()took its content to zero and there is nothing left to restore, sorelease()leaves it alone rather than returning aNaNthatangle(),magnitude_squared()andalignment()would all then spread silently. - Small operands amplify. That is the correct inverse of an attenuating
bind(), not a bug, and it is deliberately not clamped — clamping would makerelease()quietly stop being an inverse in exactly the regime where you would not notice.
Python alone is polymorphic here. Go and Rust split the two arithmetics into
Bind/BindQuantizedandRelease/ReleaseQuantized, because they are genuinely different operations and the choice is a compile-time one there. Python picks the arm from the operand’s type, and raisesTypeErrorfor anything that is neither.
Exporting
v = ph.quantize() # a SparseSegmented: ANGLES ONLY
block = ph.quantized_magnitudes() # the confidences, to keep yourself
# LOSSLESS, unlike quantize(): the accumulator as complex64, and back.
z = hv.hyper_phaser_to_np(ph) # (M,) complex64
# (re, im) per segment instead — the same bytes, for torch layers that
# reject complex dtypes. hyper_phaser_from_np takes this shape back.
r = hv.hyper_phaser_to_np(ph, real=True) # (M, 2) float32
# The array carries no mass, so pass it: without it coherence() reads 0.
ph2 = hv.hyper_phaser_from_np(model, hv.d0(), hv.p0(), z, ph.mass())
# Or let numpy coerce it: an accumulator IS an array where numpy looks.
same = numpy.asarray(ph) # (M,) complex64, == z
pair = numpy.array([ph, ph2]) # (2, M), no call per item
An accumulator is a numpy array
HyperPhaser implements numpy’s __array__, so it needs no conversion call
to be one: np.asarray(ph) is the complex64 vector, np.array([...]) over a
list is an (n, M) block, and np.abs, np.angle or a matmul take it
directly. All-pairs is then one B @ B.conj().T, whose off-diagonal entries
are exactly hv.hermitian_inner(a, b) and whose diagonal is
magnitude_squared(). Note it is not a cosine: an accumulator’s segments
are not unit-magnitude, so normalize by magnitude_squared() if that is what
you want. dtype= and numpy 2’s copy= are both honored — the default
is the same read-only zero-copy view hyper_phaser_to_np returns, and
copy=True hands you a writable one.
np.asarray(vector) stays opaque, and that is the design. A vector’s array
would be its ring offsets, where offset 0 and are one step apart yet
read as maximally distant — and np.asarray is reached implicitly, from
inside libraries you never see the inside of, so there would be no line of
your own code to suspect. code_to_np()
keeps the export explicit, and
phasor_table()
is the lift that makes the numbers mean what they look like.
An accumulator carries no such ambiguity: it already is the complex vector, and distance on it is the distance.
quantize() gives one phase per segment — the same bytes, packing and
footprint as any SparseSegmented, exactly long. That makes it a
vector which composes under bind and permute like any other.
The quantized form carries angles only. Reading it as unit phasors costs roughly
10% on similarity and all of distributional analogy (b - a + c), which needs
the radial component. The magnitudes stay on the accumulator, where
quantized_magnitudes() packs them onto a fixed 4-bit grid, two per byte — so a
caller who wants the per-segment confidences keeps that block beside the quantized form
themselves.
They are normalized by the accumulator’s own rms, and the scale is not included: a global per-vector factor cancels in both Lee and cosine, so no comparison needs it, and what survives is the confidence ordering. Four bits is the knee — measured, it matches fp32 on both similarity and analogy.
The fixed grid serves incoherent content only. It is parameter-free there,
the normalized magnitude being Rayleigh with scale whatever the
word, its support or the model. Once the observations agree the block carries
nothing: measured at 10-bit, 32 unrelated words use 11 of the 16 levels as
intended, while 32 jittered copies of one word put every segment on a single
level. The per-segment spread is , which shrinks as evidence accumulates — 0.0116 at
against a grid step of — so no renormalization recovers
it. Skip the block when coherence() runs high; that reading is what carries
the information instead.
Raising to a power
Both forms answer power(num, den), and they mean different things because the
two representations differ.
ph.power(2) # the accumulator: the FULL complex power
ph.power(1, 2) # a root
ph.power(-1) # the true inverse, 1/z
v = ph.quantize()
v.power(5, 4) # the quantized form: the phases, scaled — DEFERRED
On the accumulator: the full complex power
HyperPhaser.power is z**a = r**a * exp(i*a*theta) — the magnitude is
raised alongside the phase.
A materialized vector’s power scales only offsets because every one of its
segments is unit; there is no magnitude to raise. An accumulator’s are not
unit, so stopping at the phase would be a different operation that merely
coincides with the power when r == 1. Which is also why power(-1) here is
the genuine 1/z rather than only a conjugation.
Raising the magnitude reshapes the per-segment confidence: above 1 sharpens, so already-confident segments pull further ahead, and below 1 flattens. That is what the power means rather than a side effect — but note the consequence: the result is no longer the accumulator of any weight vector, so the cosine estimate described above no longer applies to it. Phase-only scaling would not preserve it either.
Two edges worth knowing: a cancelled segment (magnitude == 0) stays zero
rather than taking 0**a, which would be infinite for a negative exponent; and
z**0 is 1, so power(0) gives the unit phasor in every live segment, not the
all-zero vector.
On the quantized form: deferred, so chains compose
SparseSegmented.power scales the phases, which are the offsets. What differs
from a step-by-step scaling is when: the vector keeps the unscaled offsets
plus the exponent applied to them, so a chain of powers composes on the rational
and the scaling is applied once, from the base.
That is not cosmetic. Scaling step by step disagrees with the single equivalent
power once an intermediate wraps past W — wrapping then scaling is not
scaling then wrapping:
| chain | step by step | deferred |
|---|---|---|
1/2 then 1/2 | agrees with 1/4 | agrees |
3/7 then 2/5 | agrees with 6/35 | agrees |
5/4 then 7/3 | tens of ring steps off 35/12 | agrees |
The size of that gap depends on the vector — it is wherever the wrapped segments happen to land, measured in the 60–80 range on two different codebooks — but the deferred column is exactly zero every time, which is the part that is a property of the operation rather than of the instance.
Contracting exponents agree either way, because floor(floor(x/a)/b) really is
floor(x/(a*b)) and nothing wraps on the way down. Expanding ones are the
regime fractional-power encoding actually uses — Point keeps its
exponents at or above 1 — so this is the common case, not an exotic one.
An unpowered vector carries no base and pays nothing: its offsets are the
base, and only a power() call that leaves a non-unit exponent records one. A
chain that scales back to unit — power(2) then power(1, 2) — hands back the
base itself and drops the recipe again.
Note the asymmetry between the two forms. The accumulator’s power reshapes the
confidences, since raising r is part of what z**a means. The quantized form
has no confidences to reshape, so its power is purely a rotation of the phases.
Comparing
hv.lee_distance(v, other) # how far around the ring, per segment
hv.alignment(v, other) # the true cosine, in angle space
hv.overlap(v, other) # exact-offset agreement — see the warning below
v.offset(seg) # the stored phase
v.offsets() # every phase, in segment order
hv.equal(v, other) # content equality
Lower Lee is closer; chance is W/4 and the maximum W/2, per segment.
Every metric answers, and the choice is yours. A quantized vector is an ordinary hypervector, so nothing raises — which means the hazard is now a fact about the question rather than about the type. Two vectors one ring step apart in every segment are nearly identical as phasors and share no exact offset at all, so the three metrics disagree completely (measured at , ring ):
| reading | one step apart | unrelated pair | range |
|---|---|---|---|
hv.overlap | 0 | 0 | 0 … 1024, higher is closer |
hamming() | 2048 — the maximum | 2048 | 0 … 2048, lower is closer |
hv.lee_distance | 1 | 253 | 0 … 512, lower is closer |
hv.alignment | 0.99998 | 0.012 | −1 … 1, higher is closer |
Read that top-left column as the warning it is: the label metrics call the closest possible pair the furthest, because they ask whether the offsets are equal and nothing more. That is exactly right for exact-match retrieval and useless for a near-miss.
So a vector you intend to compare as phases must not be fed to the
overlap-keyed near-neighbor index. The
bytes are indistinguishable from any other hypervector’s, so nothing can warn
you at the call — pick lee_distance or alignment deliberately.
Lee or alignment?
Both read the same per-segment quantity — the ring gap — and then aggregate it differently:
lee_distanceaverages the gaps. It is a true metric, it is integer, and it is what the near-neighbor machinery can be made to bound.alignmentaverages their cosines and is therefore the exact cosine similarity: every segment is a unit phasor, so both norms are exactly and the is the normalization. Use it when you want an inner product rather than a distance.
Neither determines the other — a mean of angles and a mean of cosines are different statistics — so they can rank a pair differently, and that is not a bug in either.
See also
- Learner 💫 — the reservoir alternative. Retrieval of members from a mixture favours the Learner (its exact-match index, and L1 normalization that keeps a small member’s few clean segments); comparison of two bundles at large support favours the phasor.
- Utilities —
lee_distanceand when to reach for it. - Hypervector concepts — the phasor framing and the Lee/Hamming split.
Customizing runtime behavior
Environment Variables
All environment variables are read once on first access and cannot be changed at runtime. Unset variables use the documented default.
KONGMING_RNG
Selects the pseudo-random number generator backend used for hypervector generation.
| Value | Description |
|---|---|
philox (default) | Philox-4×64 (Random123) |
xoshiro++ | xoshiro256++: simple, fast |
pcg | PCG-DXSM: classic/compat mode |
xoroshiro++ | xoroshiro128++ |
All four are bit-parity across the Go and Rust engines. Any unrecognized
value falls back to philox.
Changing this affects all generated vectors: Sparkle offsets, Learner bundling, Cyclone patterns. Vectors generated with different backends are not compatible.
export KONGMING_RNG=xoshiro++
Querying the Current Environment
Use global_env() to inspect all active settings at runtime. Returns a GlobalEnv protobuf message — new fields added to the proto automatically appear.
>>> hv.global_env()
rng_hint: PHILOX_4X64
Misc
Display
All HyperBinary types have a compact, emoji-prefixed string representation for quick visual inspection. See HyperBinary Types for type symbols.
Python __str__ and __repr__
__str__ (triggered by print()) returns the compact emoji form:
>>> a = hv.Sparkle.from_word(hv.MODEL_8BIT, hv.d0(), "hello")
>>> print(a)
✨:🌐0x..c862,🫛0x..80e4
__repr__ (triggered by evaluating a variable in the shell or notebook) returns a detailed, developer-friendly YAML representation:
>>> a
hint: SPARKLE
model: MODEL_8BIT
stable_hash: 12345678
domain:
id: ...
pod:
seed: 12345
Serialization
# HyperBinary → protobuf message
msg = hv.to_message(sparkle)
# protobuf message → HyperBinary
obj = hv.from_message(msg)
# raw proto bytes → HyperBinary
obj = hv.from_proto_bytes(data)
# proto bytes → YAML string (for debugging)
hv.format_to_yaml(data)
Memory
The memory package provides persistent and in-memory storage for hypervectors with semantic indexing and near-neighbor search.
The core abstraction is a Chunk — an immutable identity (Sparkle) paired with a mutable semantic code (any HyperBinary). Chunks are stored in a Substrate (pluggable storage backend), queried via ChunkSelectors, and created via ChunkProducers.
| Section | Description |
|---|---|
| Chunk | The fundamental storage unit |
| Substrate & Views | Storage backends and transactional views |
| Selectors | Query builders for reading chunks |
| Producers | Write builders for creating chunks |
Chunk
The fundamental storage unit in the memory system. A Chunk mostly carries a semantic code (any HyperBinary type) along with various diagnostic information.
Structure
| Field | Type | Description |
|---|---|---|
code | HyperBinary | Semantic content (can be updated). Required — its domain/pod determines the chunk’s identity. |
id | Sparkle | identity vector, as derived from code’s domain/pod; determines the storage key. |
note | string | Human-readable annotation, primarily for debugging |
extra | protobuf Any | Extensible payload for application-specific data, primarily for debugging |
Inspection
Chunks are typically created via producers (see Producers) — or directly from a code (memory.Chunk(code, note="", extra=msg); the id derives from the code’s domain/pod) — and inspected after retrieval (see Selectors).
chunk = memory.first_picked(view, memory.by_item_key("animals", "cat"))
chunk.id # Sparkle
chunk.code # HyperBinary
chunk.note # str
chunk.extra_message() # deserialized protobuf message, or None
Substrate & Views
A Substrate is a pluggable storage backend. It provides transactional views for reading and writing chunks.
View Pattern
All storage access goes through views:
- SubstrateView — read-only, supports key lookup and prefix scanning
- SubstrateMutableView — extends SubstrateView with write staging and atomic commit (to underlying storage)
# Read-only view (context manager)
with storage.new_view() as view:
# Check if chunk exists, without actually reading it back.
exists = view.chunk_exists("animals", "cat")
cat_chunk = view.read_chunk("animals", "cat")
# Mutable view (auto-commits on clean exit, rollback on exception).
# Stage writes by running producers against the view via
# producer.produce(view) — the recommended path for batched writes.
with storage.new_mutable_view() as view:
memory.new_terminal("words", "hi").produce(view)
memory.from_sequence_members("words", "greet", members,
enable_semantic_indexing=True).produce(view)
# commits automatically
Storage Backends
InMemory
Volatile, in-process storage. All data lost on exit. Best for testing and ephemeral caches.
storage = memory.InMemory(hv.MODEL_8BIT, "my_store")
Embedded
Persistent, single-machine storage backed by an embedded key-value store. Suitable for local development and moderate-scale deployments.
storage = memory.Embedded(hv.MODEL_8BIT, "/path/to/store")
ScyllaDB (Distributed)
Distributed storage via Cassandra-compatible ScyllaDB. For high-scale, multi-node deployments.
# Not exposed yet...
Selectors
ChunkSelectors are composable query builders for reading chunks from the substrate. Each selector defines how to locate and return matching chunks.
NNS (Near-Neighbor Search)
Wraps a single attractor to perform near-neighbor search. For multiple attractors, compose them with joiner(...) first.
result = memory.first_picked(
view, memory.nns(
memory.set_members(memory.by_item_key("sets", "my_set"))))
Each attractor conceptually provides “the center of attraction” for candidates: the NNS accepts one or more attractors, to perform the actual near-neighbor search work, by interacting with underlying associative index.
Forward attractors
Roughly forward attractors try to find parts from a given a composite.
| Attractor | Modifier | Attracts |
|---|---|---|
| SetMembersAttractor | depends on selected.code.domain | All members of the Set |
| SequenceMemberAttractor | depends on selected.code.domain | Sequence member at a specific position |
| TentacleAttractor(octopus, key) | Inverse(Sparkle(model, "", key)) | Octopus value for that key |
memory.set_members(memory.by_item_key("sets", "my_set"))
memory.sequence_member(memory.by_item_key("seqs", "my_seq"), pos=2)
memory.tentacle(memory.by_item_key("records", "person"), "name")
Reverse Attractors
Roughly reverse attractors try to locate composites given a part.
| Attractor | Modifier | Attracts |
|---|---|---|
| SetAttractor(member, candidate) | Sparkle(SET_MARKER @ candidate) | All Sets in candidate containing member |
| SequenceAttractor(member, pos, candidate) | Bind(SEQ_MARKER @ candidate, Step^pos) | All Sequences in candidate with member at pos |
| OctopusAttractor(key, value) | Sparkle(model, "", key) | Octopuses with that key/value pair |
memory.set_attractor(memory.by_item_key("animals", "cat"), "sets")
memory.sequence_attractor(memory.by_item_key("animals", "cat"), 0, "seqs")
memory.octopus_attractor("color", memory.by_item_key("colors", "red"))
Analogical Reasoning
AnalogicalReasoner(dst, src, feature) performs analogical reasoning (“A is to B as C is to ?”): for each chunk c yielded by dst, it computes Bind(c.code, feature, Inverse(src)) and forwards to NNS. Model is implicit in src / feature.
Given the analogy “king is to queen as man is to ?”:
king = hv.Sparkle(model, "role", "king")
queen = hv.Sparkle(model, "role", "queen")
man = hv.Sparkle(model, "role", "man")
# Analogy: "king is to queen as man is to ?"
# src = king (the known source of the relationship)
# feature = queen (the known feature/attribute of src)
# dst = man (the target; we want to find its corresponding feature)
#
# src = king (known source), feature = queen (known relation), dst = man.
# Modifier = queen ⊗ inverse(king); applied to man → "woman".
memory.nns(
memory.analogical_reasoner(memory.with_code(man), king, queen))
Direct WithCodeModifier / WithIDModifier
For ad-hoc patterns that don’t fit a named attractor, use the primitives directly. They take a precomputed HyperBinary modifier and apply Bind(code, modifier) or Bind(id, modifier) to each yielded chunk:
memory.with_code_modifier(inner_selector, modifier_vec)
memory.with_id_modifier(inner_selector, modifier_vec)
Other Selectors
ByItemKey
Exact lookup by domain + pod.
sel = memory.by_item_key("animals", "cat")
ByItemDomain
All chunks in a given domain (prefix scan).
sel = memory.by_item_domain("animals")
WithCode / WithSparkle
Literal selector — returns a hypervector directly, no storage lookup.
sel = memory.with_code(some_hv)
sel = memory.with_sparkle("animals", "cat")
Joiner
Union of multiple selectors — returns results from each of the inner selectors.
sel = memory.joiner(
memory.by_item_key("animals", "cat"),
memory.by_item_key("animals", "dog"),
)
Range
Limits results to [start, start+limit).
limit=0 (default) implies no limit, and iteration continue until there is no more results.
sel = memory.range_sel(
memory.by_item_domain("animals"), start=0, limit=10)
OnlyDomain
Filters inner selector results by given domain.
sel = memory.only_domain(
"animals", inner_selector)
Working with Results
FirstPicked — get the first match
Returns the first chunk matching the selector. Returns an error if nothing is found.
# Returns the first matching Chunk (with .id, .code, .note, .extra_message())
chunk = memory.first_picked(view, selector)
print(chunk.id, chunk.code, chunk.note)
mem_get — eager batch read (Chunks only)
Returns every match as a list[Chunk]. No extras — any per-result SelectorExtra produced by the selector (e.g. NNS scores) is discarded. Use this when you only need the Chunks.
chunks = storage.mem_get(selector) # list[Chunk]
for chunk in chunks:
print(chunk.id, chunk.note)
lazy_selector_iter — stream Chunks with extras
Yields (Chunk, Optional[SelectorExtra]) tuples one at a time. This is the only way to access per-result SelectorExtra in Python; mem_get drops it.
# Streaming — useful for large result sets or early termination
for chunk, extra in memory.lazy_selector_iter(view, selector):
print(chunk.id, extra)
if done():
break
# Eager with extras — wrap in list()
results = list(memory.lazy_selector_iter(view, selector))
# results: list[tuple[Chunk, Optional[SelectorExtra]]]
Producers
ChunkProducers are write builders that create and persist chunks in the substrate. Each producer encapsulates the logic for constructing a specific type of chunk.
ClusterUpdater) without creating new ones. In those cases, Produce returns the updated chunk rather than a newly created one.
Producer Options
Producer options are additional information supplied to producer constructor to tweak behavior.
# `note` indiciates additional note for the new terminal chunk.
memory.new_terminal("d", "p", note="annotation")
# `enable_semantic_indexing` indicates we need to index the semantic code
# (on top of the id vector).
memory.from_set_members("d", "p", members, enable_semantic_indexing=True)
Concrete Producers
NewTerminal
Creates a chunk whose code equals its identity (a bare Sparkle). Useful for registering atoms/symbols.
with storage.new_mutable_view() as view:
memory.new_terminal("fruits", "apple", note="an apple").produce(view)
NewLearner
Creates a fresh Learner chunk for online learning.
with storage.new_mutable_view() as view:
memory.new_learner("learners", "my_learner", note="a learner").produce(view)
FromSetMembers
Creates a Set from stored members.
with storage.new_mutable_view() as view:
memory.from_set_members(
"sets",
"fruit_set",
memory.by_item_domain("fruits"),
).produce(view)
FromSequenceMembers
Creates a Sequence from stored members with positional encoding.
with storage.new_mutable_view() as view:
memory.from_sequence_members(
"seqs",
"greeting",
memory.joiner(
memory.by_item_key("words", "hello"),
memory.by_item_key("words", "world"),
),
start=0,
).produce(view)
FromKeyValues
Creates an Octopus (key-value composite) from keys and value selectors.
with storage.new_mutable_view() as view:
memory.from_key_values(
"records",
"obj1",
keys=["color", "shape"],
values=memory.joiner(
memory.by_item_key("colors", "red"),
memory.by_item_key("shapes", "circle"),
),
).produce(view)
NewDart
Creates a Dart 🎯 chunk — thrown from a tail chunk to a head chunk. Both selectors must resolve to a single chunk; the produced Dart’s bit-level value is Inv(tail.id) ⊗ head.id.
with storage.new_mutable_view() as view:
memory.new_dart(
"edges", "earth_to_moon",
memory.by_item_key("planets", "earth"),
memory.by_item_key("planets", "moon"),
).produce(view)
ClusterUpdater
Feeds an observed chunk into an existing Learner, updating its accumulated code via bundling. The bundle multiplier defaults to 1; pass an explicit override (multiple=N in Python) to fold the same observation in repeatedly.
with storage.new_mutable_view() as view:
# With explicit multiplier:
memory.cluster_updater(
learner=memory.by_item_key("learners", "my_learner"),
observed=memory.by_item_key("fruits", "apple"),
multiple=3,
).produce(view)
Notebook Quick Start
This guide walks through using Kongming HV in a Jupyter notebook, cell by cell.
| Section | Description |
|---|---|
| Notebook Platforms | Setup differences between Jupyter, Colab, and Binder |
| Interactive Notebooks | Links to existing notebooks |
| Walkthrough | Step-by-step: vocabulary, similarity, learning, binding |
Tips
- Reproducibility: Use fixed seeds in
SparseOperationfor deterministic results across reruns. - Visualization: Use
pandasDataFrames for overlap matrices — they render nicely in Jupyter. - Performance: The Rust backend is fast. Building 10,000 vectors takes under a second on
MODEL_8BIT. - Model choice: Start with
MODEL_8BITfor exploration. Switch toMODEL_10BITor larger for production workloads.
Notebook Platforms
Setup and behavior differ across Jupyter, Google Colab, and Binder. This page covers the key differences.
Try Online
| Notebook | Platform | Link |
|---|---|---|
first.ipynb | Google Colab | |
first.ipynb | Binder | |
memory.ipynb | Google Colab | |
lisp.ipynb | Google Colab |
Comparison
| Jupyter (local) | Google Colab | Binder | |
|---|---|---|---|
| Account | None | Google account required | None |
| Install | pip install in terminal beforehand | !pip install in first cell | Pre-installed via requirements.txt |
| Restart needed | No | Yes — after first install | No |
| Startup time | Instant | Fast (~5s) | Slow (2–5 min cold start) |
| Persistence | Local filesystem | Google Drive (optional mount) | Ephemeral — lost on timeout |
| GPU | If available locally | Free tier available | Not available |
| Custom packages | Full control | !pip install per session | Via requirements.txt only |
Jupyter (Local)
Install once in your terminal, then use in any notebook:
pip install kongming-rs-hv
# Cell 1 — no restart needed
from kongming import hv
For development workflows with frequent code changes, use autoreload:
%load_ext autoreload
%autoreload 2
Google Colab
Colab runs in the cloud with a fresh environment each session. Install in the first cell:
# Cell 1 — install
!pip install kongming-rs-hv
After the first install, Colab requires a runtime restart:
- Go to Runtime → Restart runtime (or use the button Colab shows after install)
- Then run the remaining cells
# Cell 2 — after restart
from kongming import hv
model = hv.MODEL_8BIT
Subsequent sessions on the same notebook will need the install cell again — Colab does not persist pip packages across sessions.
Saving work: Use google.colab.drive to mount Google Drive for persistent storage:
from google.colab import drive
drive.mount('/content/drive')
# Then use paths like /content/drive/MyDrive/...
Binder
Binder builds a Docker image from your repo’s requirements.txt and launches a Jupyter server. No account needed.
- First launch: Takes 2–5 minutes to build the environment
- Subsequent launches: Faster if the image is cached
- No install needed:
kongming-rs-hvis pre-installed fromrequirements.txt - Ephemeral: All work is lost when the session times out (~10 min idle)
# Cell 1 — works immediately, no install
from kongming import hv
requirements.txt (the environment is read-only).
Choosing a Platform
| Use case | Recommended |
|---|---|
| Daily development | Jupyter (local) |
| Quick demo / sharing | Google Colab |
| Zero-setup exploration | Binder |
| Teaching / workshops | Google Colab (students have accounts) |
| Persistent storage needed | Jupyter (local) or Colab + Drive |
Interactive Notebooks
For deeper walkthroughs, open these notebooks directly:
| Notebook | Description | Colab |
|---|---|---|
first.ipynb | Introduction to hypervectors, bind/bundle operations, and composites | |
memory.ipynb | In-memory and persistent storage, near-neighbor search with attractors, and export to disk | |
lisp.ipynb | VSA-based LISP interpreter where every data structure is a hypervector |
See also: LISP Interpreter — a full example built on the core API.
Walkthrough
A step-by-step introduction to Kongming HV in a notebook, cell by cell.
Setup
# Cell 1: Install and import
# !pip install kongming-rs-hv pandas
from kongming import hv
import pandas as pd
model = hv.MODEL_8BIT
so = hv.SparseOperation(model, 0, 1)
Building a Vocabulary
# Cell 2: Create vectors for a set of words
words = ["cat", "dog", "fish", "bird", "tree", "rock"]
vectors = {w: hv.Sparkle.from_word(model, "vocab", w) for w in words}
print(f"Created {len(vectors)} vectors")
print(f"Model: {model}, Cardinality: {hv.cardinality(model)}")
Output:
Created 6 vectors
Model: 1, Cardinality: 256
Similarity Matrix
# Cell 3: Compute pairwise overlap
data = {}
for w1 in words:
data[w1] = {w2: hv.overlap(vectors[w1], vectors[w2]) for w2 in words}
pd.DataFrame(data, index=words)
Output:
| cat | dog | fish | bird | tree | rock | |
|---|---|---|---|---|---|---|
| cat | 256 | 1 | 0 | 2 | 1 | 1 |
| dog | 1 | 256 | 1 | 0 | 1 | 2 |
| fish | 0 | 1 | 256 | 1 | 0 | 1 |
| bird | 2 | 0 | 1 | 256 | 1 | 0 |
| tree | 1 | 1 | 0 | 1 | 256 | 1 |
| rock | 1 | 2 | 1 | 0 | 1 | 256 |
The diagonal is 256 (cardinality = perfect self-overlap). Off-diagonal values are near 0-2 (random noise), confirming the vectors are nearly orthogonal.
Learning from Observations
# Cell 4: Create a learner and feed it observations
learner = hv.Learner(model, hv.Seed128(0, so.uint64()))
# "cat" seen 3 times, "dog" once, "bird" once
for _ in range(3):
learner.bundle(vectors["cat"])
learner.bundle(vectors["dog"])
learner.bundle(vectors["bird"])
print(f"Learner age: {learner.age()}")
Output:
Learner age: 5
Probing the Learner
# Cell 5: Check what the learner remembers
results = []
for w in words:
ov = hv.overlap(learner, vectors[w])
results.append({"word": w, "overlap": ov})
df = pd.DataFrame(results).sort_values("overlap", ascending=False)
df
Output:
| word | overlap |
|---|---|
| cat | ~150 |
| dog | ~55 |
| bird | ~50 |
| fish | ~5 |
| tree | ~3 |
| rock | ~1 |
“cat” has the highest overlap — roughly its weight share of the cardinality (3/5 × 256 ≈ 154). “dog” and “bird” (seen 1x each) sit near 1/5 × 256 ≈ 51. Unseen words stay at noise level.
Binding: Role-Filler Pairs
# Cell 6: Create a structured representation
# "a cat that is red"
color_role = hv.Sparkle.from_word(model, "role", "color")
animal_role = hv.Sparkle.from_word(model, "role", "animal")
red = hv.Sparkle.from_word(model, "color", "red")
blue = hv.Sparkle.from_word(model, "color", "blue")
cat = vectors["cat"]
# Bind role with filler, then bundle the pairs
learner2 = hv.Learner(model, hv.Seed128(0, so.uint64()))
learner2.bundle(hv.bind(color_role, red))
learner2.bundle(hv.bind(animal_role, cat))
# Probe: "what color?" — release the role from the learned bundle
query = hv.release(learner2, color_role)
print(f"red overlap: {hv.overlap(query, red)}") # high (~128, its bundle share)
print(f"blue overlap: {hv.overlap(query, blue)}") # ~1
print(f"cat overlap: {hv.overlap(query, cat)}") # ~1
Python Quick Start
| Section | Description |
|---|---|
| Installation | PyPI install, supported platforms, import paths |
| Quick Example | Minimal code showing bind, bundle, and overlap |
| Walkthrough | Vectors, similarity, random generation, power, learning |
See also: Notebook Quick Start for interactive Jupyter walkthroughs.
Installation
PyPI
pip install kongming-rs-hv
Supported Platforms
| Platform | Architectures | Python Versions |
|---|---|---|
| Linux | x86_64 | 3.11–3.14 |
| macOS | Apple Silicon & Intel | 3.11–3.14 |
| Windows | x86_64 | 3.11–3.14 |
Verifying Installation
import kongming
print(kongming.__version__) # e.g. "5.0.0", as of Aug. 2026. Yours should be newer.
from kongming import hv
print(hv.MODEL_8BIT) # should print 1
Import Paths
The package exposes two main modules:
from kongming import hv # hypervector operations
from kongming import memory # storage and selectors
Model constants are available directly on hv:
hv.MODEL_8BIT # 1
hv.MODEL_10BIT # 2
hv.MODEL_12BIT # 3
hv.MODEL_14BIT # 4
hv.MODEL_16BIT # 5
Docker
If you’d rather not install anything on your host, you can run kongming-rs-hv
inside a container. This works on any system with Docker — no Python, no
virtualenv, no wheel compatibility to worry about.
One-liner: throwaway Python REPL
Drop straight into a Python shell with the package preinstalled:
docker run --rm -it python:3.12-slim sh -c "\
pip install --quiet --root-user-action=ignore \
--disable-pip-version-check kongming-rs-hv && python"
--rm removes the container on exit. Nothing is persisted. Re-running reinstalls
from PyPI, which takes a few seconds. The --root-user-action=ignore and
--disable-pip-version-check flags silence pip’s root-user and upgrade notices,
which are harmless inside a throwaway container.
Reusable image
For repeat use, build a small image once:
# Dockerfile
FROM python:3.12-slim
RUN pip install --no-cache-dir --disable-pip-version-check kongming-rs-hv
CMD ["python"]
docker build -t kongming-hv .
docker run --rm -it kongming-hv
To run a script from the host instead of an interactive REPL, mount the current directory:
docker run --rm -v "$PWD":/work -w /work kongming-hv python my_script.py
JupyterLab in a container
For interactive exploration with notebooks:
# Dockerfile.jupyter
FROM python:3.12-slim
RUN pip install --no-cache-dir --disable-pip-version-check \
kongming-rs-hv jupyterlab
WORKDIR /notebooks
EXPOSE 8888
CMD ["jupyter", "lab", "--ip=0.0.0.0", "--no-browser", \
"--ServerApp.token=''", "--ServerApp.password=''"]
docker build -f Dockerfile.jupyter -t kongming-hv-jupyter .
docker run --rm -p 8888:8888 -v "$PWD":/notebooks kongming-hv-jupyter
Open http://localhost:8888 in your browser. Notebooks saved under /notebooks
are persisted to the mounted host directory.
The disabled token/password above is fine for local use. Do not expose this container on a public network without adding authentication.
Quick Example
A minimal example showing the core operations:
from kongming import hv
# Create hypervectors
a = hv.Sparkle.from_word(hv.MODEL_8BIT, hv.d0(), "hello")
b = hv.Sparkle.from_word(hv.MODEL_8BIT, hv.d0(), "world")
print(f'Overlap: {hv.overlap(a, b)}') # Near orthogonal (~1)
# Bind: result is dissimilar to both inputs
bound = hv.bind(a, b)
print(f'{hv.overlap(bound, a)=}, {hv.overlap(bound, b)=}') # ~1, ~1
# Bundle: result is similar to both inputs
bundled = hv.bundle(hv.Seed128(10, 1), a, b)
print(f'{hv.overlap(bundled, a)=}, {hv.overlap(bundled, b)=}') # high, high
What’s Happening
Sparkle.from_wordgenerates a deterministic hypervector from a word. Same word always produces the same vector.- Two unrelated vectors have near-zero overlap (~1) — random high-dimensional vectors are nearly orthogonal.
hv.bind(a, b)produces a vector dissimilar to both (low overlap). Binding is reversible.hv.bundle(seed, a, b)produces a vector similar to both (high overlap). Different seeds produce different but equally valid results.
Walkthrough
A deeper exploration of the Python API, covering vector creation, similarity, random generation, power/permutation, and online learning.
Creating Vectors
from kongming import hv
model = hv.MODEL_8BIT
# Create sparkles (atomic vectors) from words
cat = hv.Sparkle.from_word(model, "animals", "cat")
dog = hv.Sparkle.from_word(model, "animals", "dog")
# Same inputs always produce the same vector
cat2 = hv.Sparkle.from_word(model, "animals", "cat")
assert cat.stable_hash() == cat2.stable_hash()
Measuring Similarity
# Random vectors have ~1 overlap
print(hv.overlap(cat, dog)) # ≈ 1 (near-orthogonal)
# A vector is maximally similar to itself
print(hv.overlap(cat, cat)) # = 256 (= cardinality)
Using SparseOperation for Random Generation
so = hv.SparseOperation(model, 123, 456)
# Generate random sparkles
a = hv.Sparkle.random("my_domain", so)
b = hv.Sparkle.random("my_domain", so)
# Each call to so produces a new random seed
print(hv.overlap(a, b)) # ≈ 1
Power and Permutation
# Power creates a permuted vector
s = hv.Sparkle.from_word(model, "pos", "step")
s2 = s.power(2)
s3 = s.power(3)
# Different powers are near-orthogonal
print(hv.overlap(s, s2)) # ≈ 1
print(hv.overlap(s, s3)) # ≈ 1
# Inverse: power(-1) undoes power(1)
s_inv = s.power(-1)
# bind(s, s_inv) ≈ identity
# Fractional powers: pass a denominator for a rational exponent
s_half = s.power(1, 2) # s^(1/2)
s_half = s.power(1, denominator_ls=1) # same, denominator as 2**ls
s.exponent() # (1, 1) — always a (numerator, denominator) pair
s_half.exponent() # (1, 2)
s.power(6, 2).exponent() # (3, 1) — reduced, so it IS the integer power
print(s_half) # ✨:🔗pos,🌱step,💪1/2
Fractional scaling truncates toward zero, so it is lossy once the vector is
materialized. On a lazy Sparkle the exponents compose first, so
s.power(1, 2).power(2, 1) returns to s exactly; on a materialized
SparseSegmented it does not. See
Fractional powers.
Online Learning with Learner
learner = hv.Learner(model, hv.Seed128(0, 42))
# Feed observations one at a time
learner.bundle(cat)
learner.bundle(cat) # seen twice — stronger signal
learner.bundle(dog)
# The learned vector is more similar to cat (seen 2x)
print(hv.overlap(learner, cat)) # higher
print(hv.overlap(learner, dog)) # lower but above random
Examples
Standalone runnable scripts under examples/ — each demonstrates a different facet of hypervector computing. Click through for the walkthrough.
| Example | What it shows |
|---|---|
| Mexican Dollar | Analogical reasoning of “What’s the Dollar of Mexico?”: bind/bundle as the math behind analogy. |
| Word Indexer | Encoding and novel queries for 5,000 English words. |
| Bulk Storage Benchmark | Populate various substrates with thousands of chunks and measure retrieval performance. |
| Operators from Scratch | Reimplement bind and bundle in pure Python — the core math underneath the library. |
| LISP Interpreter | A full LISP where every atom, cons cell, and environment is a hypervector. For the VSA-curious. |
Operators from Scratch
Standalone script:
operators.py
This example implements the bind, release, and bundle operators in pure Python using only the low-level offset API, then verifies correctness against the library’s built-in implementations.
The script does not call hv.bind(), hv.release(), or hv.bundle() for computation — it reimplements them to show how they work at the offset level.
Bind
Per-segment offset addition modulo segment size:
for seg in range(cardinality):
result[seg] = (core_a.offset(seg) + core_b.offset(seg)) % segment_size
Properties:
- Result is nearly orthogonal to both inputs (overlap ≈ 1)
- Commutative:
bind(a, b) == bind(b, a) - Associative:
bind(a, b, c) == bind(bind(a, b), c)
Release (Unbind)
Per-segment offset subtraction modulo segment size:
for seg in range(cardinality):
result[seg] = (core_c.offset(seg) - core_k.offset(seg)) % segment_size
Properties:
release(bind(a, b), b) = a(exact recovery)- Multi-release:
release(release(bind(a, b, c), c), b) = a
Bundle
PRNG-based random selection among inputs. For each segment, a seeded PRNG picks which input vector contributes its offset. The selection probability is proportional to each input’s weight.
# Compute cumulative anchors from weights (weights sum to 1.0).
# For equal weights [0.33, 0.33, 0.33]: anchors ≈ [21845, 43690, 65535]
# For weighted [0.6, 0.2, 0.2]: anchors ≈ [39321, 52428, 65535]
cumulative = 0.0
anchors = []
for w in weights:
cumulative += w
anchors.append(int(cumulative * 65535))
for seg in range(0, cardinality, 4):
r = so.uint64() # one PRNG call → 4 × 16-bit values
for j in range(4):
dial = (r >> (48 - 16 * j)) & 0xFFFF # extract 16-bit random value
chosen = first input whose anchor >= dial
result[seg + j] = cores[chosen].offset(seg + j)
Properties:
- Result is similar to all inputs (overlap ≈ weight × cardinality)
- Not reversible — information is lost
Note: The library’s bundle folds inputs into a Learner sequentially, each replacing a weight-proportional random subset of segments. The per-segment selection frequencies match the classic draw shown above, but the exact segment choices are internal state, not public contract — so the script verifies bind/release bit-for-bit and bundle statistically.
Running
pip install kongming-rs-hv
python operators.py
Mexican Dollar
Standalone scripts:
mexican_dollar.py|mexican_dollar_memory.py
The “What’s the Dollar of Mexico?” problem is a classic demonstration of analogical reasoning with hypervectors. It shows how structured knowledge about countries can be encoded, and how algebraic operations can answer analogy questions without explicit programming.
The Problem
Given knowledge about three countries:
| Country | Code | Capital | Currency |
|---|---|---|---|
| USA | USA | Washington DC | Dollar |
| Mexico | MEX | Mexico City | Peso |
| Sweden | SWE | Stockholm | Krona |
We want to answer questions like:
- “What is the Dollar of Mexico?” → Peso
- “What is the Washington DC of Mexico?” → Mexico City
- “What is the Dollar of Sweden?” → Krona
How It Works
Each country is encoded as a bundled set of role-filler bindings:
To find “the Dollar of Mexico”, we compute a transfer vector from US to Mexico:
Then apply it to Dollar:
The result will have high overlap with Peso — the analogical answer.
The same transfer works for Sweden:
Code (Manual)
Full script: mexican_dollar.py. The essence — each country is a bundle of role ⊗ filler pairs, and one release + one bind answers the analogy:
us_record = hv.bundle(hv.Seed128.random(so),
hv.bind(country_code, usa), hv.bind(capital, dc), hv.bind(currency, dollar))
# ... mexico_record, sweden_record likewise ...
transfer_to_mexico = hv.release(mexico_record, us_record)
mexican_dollar = hv.bind(dollar, transfer_to_mexico)
hv.overlap(mexican_dollar, peso) # 32/32 — the answer
hv.overlap(mexican_dollar, dollar) # 2 — noise
hv.overlap(mexican_dollar, krona) # 0 — noise
The same transfer answers “the Washington DC of Mexico?” (→ mexico_city, 29/32) and, via release(sweden_record, us_record), “the Dollar of Sweden?” (→ krona, 26/32).
Code (with AnalogicalReasoner)
Full script: mexican_dollar_memory.py. When the country records live in storage — filler terminals plus one Octopus per country, staged via the producer API — analogical_reasoner does the transfer for you:
result = memory.first_picked(view,
memory.nns(
memory.analogical_reasoner(
memory.with_code(mex_code), src=us_code, feature=fillers["USD"])))
print(result.id) # → ✨:🌱MXN
analogical_reasoner computes the transfer vector feature ⊗ inverse(src) internally and uses near-neighbor search to find the best match in memory — no manual algebra needed.
Why It Works
The transfer vector captures the structural mapping between the two records. When applied to any filler from the US record, it maps it to the corresponding filler in the Mexico record — because the role-filler binding structure is preserved by the algebra.
This is a form of analogical reasoning: no explicit rules, no lookup tables — just algebraic operations on high-dimensional vectors.
See Also
- Concepts: Operators — algebraic foundations
- Operators — bind, release, bundle
- Octopus — key-value composite used for country records
- Memory: Selectors —
analogical_reasoner,nns,with_code - Near-neighbor search — how the reasoner finds answers
Bulk Storage Benchmark
Standalone script:
bulk_storage.py
This example populates a storage with a large number of random terminal chunks, then queries a few by key to verify correctness. It demonstrates how to batch-create items and measure throughput.
Note associative index is also prepared in the process, and near-neighbor search is available immediately upon successful conclusion of all writing.
Motivated readers can further improve this script to test various producers or selectors.
What it does
Full script: bulk_storage.py. The core loop is three lines — pick a backend, write N terminals through mem_set, then spot-check ids:
storage = memory.InMemory(args.model) # or memory.Embedded(args.model, path)
for i in range(args.count):
storage.mem_set(memory.new_terminal(args.domain, str(i)))
# verify: stored id must equal the deterministic Sparkle for the same key
chunk = storage.get(args.domain, str(idx))
assert hv.equal(chunk.id, hv.Sparkle.from_word(args.model, args.domain, str(idx)))
The script wraps this with argparse (count, model, backend, path), timing, and throughput reporting.
Usage
# Default: 10K chunks, in-memory storage substrate.
python bulk_storage.py
# Embedded (disk-backed storage substrate).
python bulk_storage.py --backend embedded
# Embedded with a specific path (tip: use a tmpfs mount for near-in-memory speed)
python bulk_storage.py --backend embedded --path /dev/shm/my_bench
# Custom count
python bulk_storage.py -n 100000
# Different model, 1 implies MODEL_8BIT model, etc.
python bulk_storage.py -n 10000 --model 1
Word Indexer
Standalone script:
word_indexer.py
This example encodes ~5,000 English words as Sequences of per-letter Sparkles, then queries them by exact word or by positional suffix (“six-letter words ending in er”, “eleven-letter words ending in tion”) using multi-attractor near-neighbor search.
It demonstrates four ideas together:
- Using
Sparkleas a stable per-symbol code (one Sparkle pera–z). - Using
Sequencewith aPod-derived seed so chunks are addressable both by word (exact) and by structure (positional). - The ChunkProducer API (
new_terminal,from_sequence_members,joiner) staged through a batchedSubstrateMutableViewviaproducer.produce(view). - Multi-attractor
similarsearch overSequenceAttractors for positional conjunctive queries.
The general idea
letters domain words domain
───────────── ────────────
"a" → Sparkle_a "the" → Sequence(t, h, e)
"b" → Sparkle_b "language" → Sequence(l, a, n, g, u, a, g, e)
"c" → Sparkle_c ...
... Pod = word (exact lookup key)
"z" → Sparkle_z note = word (recoverable in results)
members = letter Sparkles in order
- Letters as Sparkles. Pre-write 26 random-looking
Sparkles, one pera–z, into alettersdomain vianew_terminal(letters, ch). Each letter’s Pod is the letter itself, so you can fetch it byby_item_key("letters", "e"). - Words as Sequences. Each word is a
Sequencein awordsdomain whose ordered members are the letter-Sparkles spelling it, built byfrom_sequence_members(...)with ajoiner(...)of per-letterby_item_keyselectors. The Sequence’s Pod is the word, so exact lookup isby_item_key("words", "language"). notecarries the word string. Each word-chunk is written withnote=<word>, sochunk.noterecovers the word in result loops without decoding the Pod.
Batched writes via the ChunkProducer API
This example uses the producer API end-to-end. Producers compute their
chunks at produce() time against a mutable view, mirroring Go’s
producer.Produce(ctx, view) and Rust’s producer.produce(view, index).
Storage’s new_mutable_view() is a context manager with transactional
semantics:
- All writes staged by
producer.produce(view)calls between__enter__and__exit__go into a single batch. - Clean exit auto-commits; an exception inside the block discards everything.
view.commit()mid-block flushes the current batch and lets you continue staging — useful for pacing memory pressure on large ingests.
Letters and words go into two separate views; the second commits every
BATCH_SIZE = 1000 words:
with storage.new_mutable_view() as view:
for ch in "abcdefghijklmnopqrstuvwxyz":
memory.new_terminal("letters", ch).produce(view)
# auto-commits on __exit__
with storage.new_mutable_view() as view:
for i, w in enumerate(words, start=1):
members = memory.joiner(*[memory.by_item_key("letters", ch) for ch in w])
# enable_semantic_indexing=True: index the Sequence's code so suffix
# queries (sequence_attractor) can find words by structure.
memory.from_sequence_members(
"words", w, members, note=w, enable_semantic_indexing=True,
).produce(view)
if i % BATCH_SIZE == 0:
view.commit()
# trailing writes auto-commit on __exit__
See Substrate & Views for the full view API.
Multi-attractor NNS
A sequence_attractor(member_selector, pos, domain) is a positional constraint: “Sequences in domain whose member at pos overlaps with member_selector”. Position is 0-based.
similar(joiner(...)) evaluates all attractors and ranks Sequences by combined overlap. With multiple attractors, the result is a conjunction — a chunk must satisfy each positional constraint to score well.
For “six-letter words ending in er”:
memory.similar(
memory.joiner(
memory.sequence_attractor(memory.by_item_key("letters", "e"), 4, WORDS_DOMAIN),
memory.sequence_attractor(memory.by_item_key("letters", "r"), 5, WORDS_DOMAIN),
)
)
This returns Sequences with e at index 4 and r at index 5 — i.e., the last two characters of a six-letter word.
For “eleven-letter words ending in tion”, anchor t/i/o/n at positions 7/8/9/10.
Counting and ranged results
storage.mem_get(selector) returns the full ranked result list as a Python list. Two helpers shape the output:
| Call | Use |
|---|---|
mem_get(nns(...)) | Get every match. len(...) is the count. |
mem_get(range_sel(nns(...), start, limit)) | Materialize a window — useful for top-N. |
range_sel(inner, start, limit) consumes its inner selector, so to demonstrate both count and top 10 the example builds the NNS selector twice (cheap; the substrate work dominates).
See Working with Results for more on shaping selector output. When you need per-result SelectorExtra (e.g. NNS scores) or lazy iteration, reach for memory.lazy_selector_iter(view, selector) — mem_get returns Chunks only.
Running
pip install kongming-rs-hv
python examples/word_indexer/word_indexer.py
Expected output shape:
Ingested 4982 words in 40s.
by word 'the': 1 match(es) [0.9 ms]
1. the
by word 'people': 1 match(es) [0.1 ms]
1. people
****er (6 letters): 712 match(es) [~30 ms]
1. closer
...
*******tion (11 letters): 847 match(es) [~25 ms]
1. information
...
Approximate timings on an Apple Silicon laptop with the InMemory backend:
| Operation | Time |
|---|---|
| Ingest ~5,000 words via producer API | ~40 s |
Exact lookup via by_item_key | <1 ms |
Multi-attractor search (2 attractors, e.g. *****er) | ~30 ms |
Multi-attractor search (4 attractors, e.g. *******tion) | ~25 ms |
A note on enable_semantic_indexing
For NNS by composite structure (i.e. “find Sequences whose member at
position N matches X”), each word’s producer is constructed with
enable_semantic_indexing=True. This impresses the Sequence’s code into the
associative index alongside the chunk’s id-Sparkle (which is always
indexed). Without the flag, only the id is indexed and
sequence_attractor queries return zero hits.
The letter terminals are written without the flag because their code is the id-Sparkle, so id-only indexing is sufficient.
Switching to persistent storage
InMemory is fine for a demo. For a persistent store, swap one line:
storage = memory.Embedded(MODEL, "/path/to/db")
Everything else is identical.
Data attribution
Word-frequency data in top5000.txt is sourced from www.wordfrequency.info (top-5000 English words). Please credit the source when reusing this data.
Format (tab-separated, no header):
Rank Word POS Frequency Dispersion
See Also
- Sparkle ✨ — per-symbol code used for letters
- Sequence 📿 — ordered composite used for words
- Attractors —
sequence_attractorand friends - Near-Neighbor Search —
nnsover multiple attractors - Substrate & Views — batched mutable views
- Working with Results —
range_sel,mem_get
LISP Interpreter
A LISP interpreter where every data structure — atoms, cons cells, lists, closures — is encoded as a hypervector. No traditional memory allocation, no pointers, no garbage collector. All computation happens through hypervector algebra.
Two Implementations
The LISP interpreter ships in two forms, both feature-identical:
Pure Python (pylisp) | Rust (kongming_rs.lisp) | |
|---|---|---|
| Source | Open-sourced in examples/pylisp/ | Compiled into kongming-rs-hv |
| Readable | Yes — ~500 lines of annotated Python | No — compiled Rust binary |
| Performance | Slower (Python overhead per operation) | Faster (native code) |
| Import | from kongming.pylisp import LispEnv | from kongming.lisp import LispEnv |
| Dependencies | kongming-rs-hv (for hypervector primitives) | Included in kongming-rs-hv |
| Use case | Learning, debugging, extending | Production, notebooks |
Rust (built-in)
The kongming-rs-hv package includes a Rust-based LISP interpreter built directly on the internal Rust API and primitives. This implementation is compiled into the Python wheel and accessible via from kongming.lisp import LispEnv.
Since it operates on Rust-native hypervector types with zero Python overhead, it delivers the best performance for production use.
Python (open-source)
For research and study, we provide a pure-Python implementation of the same interpreter, built entirely on the public Python API of kongming-rs-hv. It mirrors the Rust implementation’s architecture but uses Python-level operations (hv.bind, hv.bundle, hv.release, etc.), making the underlying hypervector mechanics fully transparent and easy to modify.
This implementation is ideal for:
- Understanding how LISP primitives map to hypervector operations
- Experimenting with alternative encodings or evaluation strategies
- Teaching and prototyping
Quick Start
pip install kongming-rs-hv
# Pure Python
from kongming.pylisp import LispEnv
env = LispEnv()
env.eval("(CAR (QUOTE (A B C)))") # => "A"
env.eval("(CDR (QUOTE (A B C)))") # => "(B C)"
env.eval("(CONS (QUOTE A) (QUOTE B))") # => "(A . B)"
# Rust (same API, same results)
from kongming.lisp import LispEnv
env = LispEnv()
env.eval("(CAR (QUOTE (A B C)))") # => "A"
Supported Forms
McCarthy’s 7 Primitives (1960)
| Form | Example | Result |
|---|---|---|
QUOTE | (QUOTE (A B C)) | (A B C) |
CAR | (CAR (QUOTE (A B C))) | A |
CDR | (CDR (QUOTE (A B C))) | (B C) |
CONS | (CONS (QUOTE A) (QUOTE B)) | (A . B) |
ATOM | (ATOM (QUOTE A)) | T |
EQ | (EQ (QUOTE A) (QUOTE A)) | T |
COND | (COND ((EQ (QUOTE A) (QUOTE B)) (QUOTE NO)) (T (QUOTE YES))) | YES |
Extensions
| Form | Description |
|---|---|
LAMBDA | Anonymous functions with curried beta-reduction and variable shadowing |
LABEL | Recursive self-reference (enables recursion without mutation) |
DEFINE | Bind a name to a function in the environment |
Examples
# Lambda
env.eval("((LAMBDA (X) (CAR X)) (QUOTE (A B C)))") # => "A"
# Define a reusable function
env.eval("(DEFINE SECOND (LAMBDA (L) (CAR (CDR L))))")
env.eval("(SECOND (QUOTE (X Y Z)))") # => "Y"
# Recursion with LABEL
env.eval(
"(DEFINE LAST (LAMBDA (L) "
" ((LABEL REC (LAMBDA (X) "
" (COND ((ATOM (CDR X)) (CAR X)) "
" (T (REC (CDR X)))))) L)))"
)
env.eval_full("(LAST (QUOTE (A B C)))") # => "C"
How It Works
Each LISP value is a Sparkle — a sparse binary hypervector seeded by
its content. Atoms like A, B, CAR are sparkles in a symbol domain.
A cons cell (a . b) is encoded as:
cell = bundle(bind(a, LHS), bind(b, RHS))
where LHS and RHS are fixed tag sparkles. The cell is stored under a
fresh random sparkle id. To extract:
car(id) = cleanup(release(cell, LHS))
cdr(id) = cleanup(release(cell, RHS))
The release operation is noisy — it produces an approximate result.
Cleanup uses near-neighbor search (NNS) over the substrate’s
associative index to find the exact stored sparkle that best matches
the noisy probe.
File Structure
examples/pylisp/
__init__.py # Package entry point
types.py # HyperBinary type alias
env.py # LispEnv: domains, symbols, lexicon, substrate
cons.py # Cons cells: cons, car, cdr, cleanup via NNS
reader.py # S-expression tokenizer and parser
evaluator.py # Single-step and fixed-point evaluator
lambda_.py # Beta-reduction with currying and shadowing
printer.py # Hypervector → S-expression display
test_pylisp.py # 16 tests mirroring the Rust integration suite
Storage Backends
# In-memory (default, volatile)
env = LispEnv()
# Persistent (Embedded disk-backed)
env = LispEnv(path="/tmp/my_lisp_db")
Running Tests
pip install pytest kongming-rs-hv
pytest examples/pylisp/test_pylisp.py -v
Notebook
We provide a Colab notebook that runs both implementations side by side, demonstrating correctness parity and performance comparison:
References
- Hey, Pentti, We Did it!: A fully Vector-Symbolic Lisp — the paper that inspired this implementation
- Peter Norvig’s (How to Write a (Lisp) Interpreter (in Python)) — the original Lispy that the Python implementation builds upon
Dependency Parser
Everything in this book so far — Sparkles, composites, learners, pools, near-neighbor search — was built for a purpose: a demonstration that VSA can offer a unique and novel perspective in cognitive computing / AI.
This chapter serves that purpose: a dependency parser in which the entire language model is a hypervector substrate.
Unlike traditional NLP with heavy reliance on explicit frequency tables, and unlike neural networks where gradients are computed via backpropagation, our training/inference features:
- A transparent representation of the underlying language models that encourages inspection and enables incremental improvements;
- An efficient representation far more compact than existing models, see Evaluations;
- An efficient computation with mostly binary operations, no need for floating-point computations or expensive GPUs;
- The language models are generic in the sense that new languages can be added without language-specific idiosyncrasy or much tweaking.
Wernicke’s area in the brain is widely hypothesized to host the generic neural circuitry for language understanding: the solution I hope to present here will be the computational counterpart of it.
For readers new to this topic (or to this project), the best starting point is my paper, Cognitive modeling and learning with sparse binary hypervectors (full citation in the introduction): it lays the foundation — sparse binary hypervectors and their operators — that everything in this chapter builds on.
The project is divided into the following pages:
| Section | Description |
|---|---|
| Live demo | Parse a sentence in your browser — the decoder compiled to WebAssembly |
| Introduction | This project at a glance |
| Training | Building language models |
| Decoding | Viterbi retrieval under a beam |
| Evaluations | Held-out quality, speed, and footprint |
| Discussions | Discussions, improvements, capacity, etc. |
Introduction
The original idea came from a random bump into the stanza NLP package (from Stanford) and its web-based rendering.
What the website shows is a dependency parse for human languages: the sentence split into tokens, each token tagged with its part of speech, lemma, and named-entity type, and, for the interesting part, every token is attached to a head token by a labeled edge (subject-of, object-of, modifier-of, …). The nodes and edges form a dependency tree representing the sentence’s grammatical structure.
Parsing is one of the fundamental tasks in NLP, and serves as a pre-processor for many downstream language-understanding applications: information extraction, question answering, knowledge-graph construction all start from exactly these parse trees.
A brief history, and where we are
The dominant technique before neural networks was the HMM family: Hidden Markov Models and their hierarchical variants, where decoding recovers a sequence of latent states with learned transition and emission probabilities. Most modern parsers have since switched to specially-trained neural networks, which lifted accuracy substantially at the cost of opaque models, heavy computation, and hundreds of megabytes of storage per language model.
State-space models, generally
HMMs belong to a much larger family: state-space models (SSMs). The shared idea is fundamentally simple: a latent state summarizes everything about the past that matters, a transition rule evolves it step by step, and each observation is emitted from the current state. Choose discrete states and you have the HMM; choose linear-Gaussian ones and you have the Kalman filter; let a network learn the transition and you have an RNN. Under this lens, sequence understanding is always the same job: maintain a compressed state, and keep it honest against the observations.
SSMs are having a renaissance. Modern deep-learning variants (the S4/Mamba line) rediscovered that a recurrent state gives linear-time, constant-memory sequence processing, where attention pays quadratic cost and must hold the whole window, and made it competitive at scale.
The classical virtues of SSMs never went away either: explicit and inspectable states, principled inference (Viterbi decoding, Kalman filtering) instead of learned approximation, and reasonable model performance from a modest amount of data. What killed the classical SSM in practice was the state-space explosion: in NLP domain, rich linguistic states make the transition tables astronomically large and their statistics hopelessly sparse.
The parser in this project is best understood as a revival of the hierarchical HMM rebuilt on hypervectors, attacking that exact weakness head-on. High-dimensionality offers practically unlimited orthogonal vectors to work with, superposition keeps an enormous state space, potentially hierarchical in the same shape, and evidence pooling tames the sparse statistics.
It keeps the SSM virtues the neural approximations have given up: transparency and inference you can trace. The latent states are still there: they are spines of grammar edges, and decoding is still Viterbi over a beam. What changed is the substrate: instead of explicit probability tables, every statistic lives in superposed sparse binary vectors, learned over time and read back efficiently and on-demand by similarity.
The goal
Functionally, the parser sets out to do what the stanza demo does: given a tokenized sentence in English, Chinese, or any desired language in the future, it emits the same artifacts: per-token part of speech, lemma, named-entity spans, and the labeled head edges that form a complete dependency tree. Text corpora of different languages are condensed into their own language models which can generalize, and the same engine runs decoding with no language-specific priors or code paths.
Matching that output contract, however, is the baseline rather than the point. The focus here is not to achieve performance parity with state-of-the-art neural networks, but to demonstrate the feasibility of an alternative model with the following characterizations:
- compaction — the trained model for 2 languages (English and Chinese for now) fits in tens of MBs (see Evaluations for more details);
- efficiency — training is a single pass, and decoding is mostly integer/bitwise computation with no GPU needed. Additionally, online learning can be added if desired;
- transparency — every decoding decision is transparent: you can print, trace, and improve it incrementally.
Bootstrapping
Unsurprisingly, this parser learns from annotated trees. The annotations are produced by an existing parser (stanza, following the Universal Dependencies conventions): a typical teacher–student setup. The teacher supplies a training tree for each incoming sentence, and the student learns to reproduce and generalize them in an entirely different representation. The quality ceiling is therefore the teacher’s; the demonstration is about the representation, not about outrunning the state of the art.
Further reading
The rest of the chapter walks the pipeline:
- Training: how trees become substrate writes;
- Decoding: how token streams become trees again;
- Evaluations: measured quality;
- Discussions: why it works, and what’s next.
References
State-space models, classical and modern:
- L. R. Rabiner — A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition. Proc. IEEE 77(2), 1989. DOI
- S. Fine, Y. Singer, N. Tishby — The Hierarchical Hidden Markov Model: Analysis and Applications. Machine Learning 32(1), 1998. DOI
- A. Gu, K. Goel, C. Ré — Efficiently Modeling Long Sequences with Structured State Spaces (S4). ICLR 2022. arXiv:2111.00396
- A. Gu, T. Dao — Mamba: Linear-Time Sequence Modeling with Selective State Spaces. 2023. arXiv:2312.00752
- T. Dao, A. Gu — Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Mamba-2). ICML 2024. arXiv:2405.21060
Parsing and annotations:
- P. Qi, Y. Zhang, Y. Zhang, J. Bolton, C. D. Manning — Stanza: A Python Natural Language Processing Toolkit for Many Human Languages. ACL 2020 (System Demonstrations). arXiv:2003.07082
- M.-C. de Marneffe, C. D. Manning, J. Nivre, D. Zeman — Universal Dependencies. Computational Linguistics 47(2), 2021. ACL Anthology
Training
Training turns a corpus of parsed sentences into a substrate, in a single pass.
This page walks the training pipeline conceptually: from raw text to what, exactly, ends up as a fully-functional language model.
Preparing the corpus
For reference, we used ~4000 English and ~4000 Chinese sentences from the public Wikipedia corpus for training. The training itself can be done on a single MacBook Air M2 in ~10 minutes.
Preparing the text
The corpus starts as plain text, one batch per language: curated sentences covering the vocabulary and constructions the model should absorb and later generalize in typical decoding scenarios.
The text is split into individual sentences up front, and each sentence is handed to the annotation step on its own, one sentence per request.
Bootstrapping the parsed trees
A teacher parser (i.e., stanza) annotates each incoming sentence: tokens, part of speech, lemma, morphological features, named-entity spans, and the head arc that makes the dependency tree. The annotated sentences are stored as compact per-language archives, which can be loaded when needed: development or production of the training pipeline doesn’t need the live parser or the raw text, for efficiency reasons.
Beyond various annotations, the training pipeline further re-constructs a dependency tree per sentence. The tree has a single ROOT, with each leaf node mapping to a surface token and each arc annotated with its dependency relation, following the Universal Dependencies conventions.
From trees to spines
The local grammar and syntactic dependency are captured by the nodes and edges of the dependency tree.
A feats captures a unique combination of rich linguistic features, such as part-of-speech, lemma, and morphological features. An edge, on the other hand, is the parent and child feats, annotated with the incoming dependency label, as a deterministic Sparkle instance.
Each surface token is ultimately emitted by its spine, the hierarchy of interlocked edges from the root down. Siblings under a subtree share edges up to the subtree root, before diverging into their unique edges.
Within the state-space setup, the latent state at token t is that token’s spine, namely its full hierarchical path in the tree, from the root edge down to its leaf. Concretely, a state is a Sequence whose members are the spine’s edges.
Three properties make this state space feasible where classical HMMs can choke:
- Representation of states: the space of possible spines is combinatorially vast, which hypervectors have no problem handling. A state, at its core, is conceptually just another hypervector, sharing the same shape as any other state, though of a potentially different length. Practically, thanks to lazy materialization, composing a state on the fly reduces to simple bookkeeping, with very little extra cost;
- No tabulation: instead of highly sparse frequency tables, a learner is a far more natural representation for encoding probabilities, only at cells where transitions do happen. Furthermore, LearnerPool offers an elegant solution for the high dynamic range of fan-outs;
- Content-addressable by construction: two surface tokens emitted by the same grammatical path share the same state, by construction: that identity is what lets transition statistics pool.
The downstream inference task, naturally, is to recover the most likely sequence of states/spines, before reconstructing the dependency tree.
Stepping back from a broader perspective, hierarchical inference over such a state space is a generic problem, applicable well beyond linguistic parsing: anywhere the potential state space is too immense to tabulate. A robust training/inference pipeline that accommodates a vast and rich state space is a valuable by-product of this project in its own right.
What is learned
Two kinds of learning/writes happen, side by side.
The inventory — ordinary chunks, written once (create-if-missing, idempotent across repeats):
- every distinct feats: the collection of all known combinations of linguistic features in a language;
- every distinct edge: its parent-and-child pair of feats, acts as the skeleton of the language;
- every distinct token — an Octopus containing feats, lemma, and surface text (this is where the lemma can be recovered from the surface token at decode time);
- every named entity (see below).
The statistics — writes into one per-language LearnerPool, three conceptual families:
| family | address → content | answers at decode time |
|---|---|---|
| out | sibling edge → next sibling edge | “after this edge, what comes next at this level, and at what probability?” |
| down | first-child edge → parent edge | “whose child is this?”, which supports the exploration/climb upward |
| obs | surface text → leaf edge | “which leaf edges can emit this surface token?” |
Every occurrence adds an extra piece of information, and the frequency is the statistic: a transition seen a thousand times reads back a thousand times stronger than one seen once, at least in principle.
Nothing is normalized at training time, as a self-normalization process is at play: observations compete for a Learner’s fixed representational budget, so read-back strengths are effectively relative probabilities.
The sentinels: BEGIN and END
Every sibling chain is conceptually bracketed:
BEGIN → e₁ → e₂ → … → END. The two brackets are treated very differently,
and the asymmetry is deliberate:
END is trained. The last child’s out-transition to END is recorded like any other, so every edge carries a measured probability that its chain closes after it, which is needed by the decoder.
BEGIN is not trained as a transition source. “How do chains open?” has enormous fan-out at fine granularity (thousands of distinct edges): one address accumulating a transition to every chain-opening edge in the corpus would saturate its pool members and the statistic would drown. Instead, chains open through the down family — the first child’s edge is the parent’s climb anchor.
So BEGIN’s information is actually trained and recorded in the down family instead of the out family. Every down entry is implicitly a BEGIN target: an edge that begins a subtree under its parent (the sentence root is merely the outermost instance). The same relation is addressed from the opposite — and favorable — low-fan-out side: sharded per parent across thousands of addresses instead of concentrated at one — and the decoder recovers the chain-opening probability hop-wise through observation confidence.
Named entities
Entities get special treatment because they behave like single tokens with internal structure. Entity members carry the entity’s signature (a content hash), so entity-internal edges are distinct identities — “York” under “New York” is not confused with a generic proper-noun attachment.
An entity’s internal membership is trained exactly once, as the members are fixed for each named entity, by definition.
See also
- Composites: encoding sequences and hierarchical states
- Learner: encoding transition probabilities
- LearnerPool: accommodating the high dynamic range of fan-outs
Decoding
Decoding inverts training: tokens arrive one at a time, and the linguistic parser must recover the most likely sequence of states that could have emitted them, then eventually convert that sequence back into a dependency tree.
The engine is a Viterbi beam over the hierarchical state space, and this page walks one token’s journey through each step.
What the decoder carries
Between tokens, the decoder maintains a beam: the best hypotheses so far. Each surviving state itself is a spine, outlining the hierarchical path for the previous token, plus its accumulated Viterbi score . True to form, the beam slice itself is stored as a superposition of all surviving state vectors, weighted by their confidence, plus a parallel superposition of backpointers recording where each state came from.
At the start of a sentence the beam holds a single seed state anchored at
BEGIN, and each primed language contributes its own seed — the beam
arbitrates between languages on evidence alone, with no explicit language switch anywhere in the engine: we have a natural way to handle multi-lingual tokens.
Decoding cycle
1. Start as candidate leaves
The obs family answers: which leaf edges may have emitted this word? Each answer is a candidate leaf, already weighted by observation frequency.
2. Climb
From each candidate leaf, the decoder climbs the down family: each hop reads “whose child is this edge?” and yields the plausible parents, again frequency-weighted. The result is a set of extended candidate spines, each carrying a joint observation confidence.
3. Graft and score
Each candidate spine may attach to each of the beam’s previous states at any layer of that state’s spine. For every (prev_state, layer, candidate) triple, admission is a single fitness test to the out family: does the candidate’s top edge fit the prev_state’s edge at this layer? The answer becomes the transition confidence. Two structural rules apply:
- The root gate. Layer zero hosts only root edges; a mid-tree edge proposing itself as a new root is structurally illegal and is dropped without a read. Genuine root openings get a uniform prior instead — this is the flip side of
BEGINbeing untrained (see Training). - The conclusion discount. Grafting at layer L implicitly closes every existing layer below L for the previous state: each close-pending level pays its measured END cost. An expected closing costs almost nothing, a surprising one costs considerably more. This is how the decoder balances “attach deep, continue the phrase” against “attach high, close the clause” with statistics instead of heuristics.
The candidate’s score is then the classic Viterbi:
4. Ghosts
If no real candidate survived the placement for the current beam, that might be the case for an out-of-vocabulary word, or a simple typo. The decoder asks each beam state’s leaf edge for its predictions without observations. The best few become ghost candidates, priced low but non-zero, while participating in continuing the beam.
One guard applies: a ghost is purely prediction, not an observation, so any named-entity claim it carries is checked against the actual input text and stripped on mismatch — no phantom entities.
5. Select
All admitted hypotheses, real and ghost, are ranked together by confidence and only the top survive. The new states are superposed, along with their backpointers, and the cycle begins.
Backtrace
When the sentence ends, the best-scoring endpoint is unwound through the backpointers, recovering the winning state sequence: one spine per token, in order. This is the Viterbi answer: the most likely path through the state space, given everything observed so far.
Reassembly
The spine sequence is folded back into a dependency tree: tokens are bucketed by their parent edge, the is_head marker identifies exactly the head member of each subtree, to which all other members attach.
Along the way each token’s lemma is recovered from its trained token record, and entity spans are re-emitted from the carried annotations. The output is the same artifact the teacher produced: a full dependency parse.
Properties worth noticing
- Streaming: one token in, one beam update; the carried state (of the decoder) is the superposition of surviving hypotheses, fixed size regardless of sentence length and hypothesis count.
- Inspectable: every admission, discount, and ranking above is an integer you can print: there is no layer of the decision you cannot open.
See also
- LearnerPool — the access-circle reads under every step.
Evaluations
Setup
Note: the numbers below were measured on the Rust engine over the full held-out validation tier (the Go and Rust engines are kept at bit-parity and decode identically).
Combined corpus of 4231 English + 4231 Chinese sentences for training; the statistics live in a unified LearnerPool (MODEL_8BIT) per language.
Validation tier: 950 held-out sentences — 484 English (5.8K tokens) and 466 Chinese (5.1K tokens), never seen in training.
Substrate stats
The entire trained model — every transition statistic and open-class inventory for English and Chinese — is a 17 MB substrate on disk.
The trained substrate: 336,564 chunks, with Payload types:
- 192,731 SPARKLE;
- 58,129 OCTOPUS;
- 85,704 LEARNER, that made up 2 LearnerPools;
Pool health, per 65,536-member language pool:
| en | zh | |
|---|---|---|
| trained members | 46,339 | 39,365 |
| open / closed | 42,643 / 3,696 | 35,036 / 4,329 |
| total load (Σ age) | 401,792 | 457,194 |
| mean member age | 8.7 | 11.6 |
Held-out parse quality
Production configuration (coarse tier on), per language and combined (full-tier run on the pre-redesign substrate; the sampled tables below are current):
| metric | English | Chinese | mixed |
|---|---|---|---|
| full-parse | 99.2% | 99.4% | 99.3% |
| head attachment | 74.9% | 57.0% | 66.5% |
| upos | 95.5% | 87.6% | 91.8% |
| deprel | 77.6% | 64.3% | 71.3% |
| lemma | 92.9% | 92.1% | 92.5% |
| entity recall | 56.0% | 63.5% | 59.2% |
| entity precision | 62.5% | 76.2% | 68.1% |
Entity matching is a multiset match on (type, text) between the gold entities and the surfaced ones, over parsed sentences.
Training corpus vs held-out
The same sweep per language over sampled tiers (English at 10%, Chinese at 5%), on the consolidated substrate: the training corpus bounds what the substrate retained; the held-out gap is the generalization cost.
| metric | en training (422) | en val (65) | zh training (215) | zh val (24) |
|---|---|---|---|---|
| full-parse | 98.6% | 96.9% | 98.6% | 100% |
| head attachment | 81.9% | 71.1% | 70.1% | 58.5% |
| upos | 97.5% | 93.5% | 91.8% | 85.3% |
| deprel | 89.8% | 77.3% | 78.2% | 63.8% |
| lemma | 96.6% | 91.3% | 97.4% | 91.7% |
| entity recall | 77.3% | 62.9% | 76.6% | 72.7% |
| entity precision | 80.1% | 75.3% | 78.3% | 78.0% |
The coarse tier’s contribution
Ablating the coarse-to-fine backoff on the same substrate and the same full validation tier (tier off → on), head attachment:
| slice | tier off | tier on | Δ |
|---|---|---|---|
| English (484) | 72.7% | 74.9% | +2.2 |
| Chinese (466) | 54.5% | 57.0% | +2.5 |
| mixed (950) | 64.1% | 66.5% | +2.4 |
The gains come from trained coarse-class evidence rescuing transitions the fine-grained statistics never saw — not from structural guessing.
Decode throughput
Single decoder, sequential decode, on the same MacBook Air that trains the model in ~12 minutes (sampled tiers, consolidated substrate):
| combined tokens/s | val tokens/s | |
|---|---|---|
| English | 21.9 | 20.8 |
| Chinese | 4.1 | 4.7 |
The width-addressed dense posting index (no hashing on the decode-side Collect/Add) shaved ~10 ms/token off both languages on top of the pool consolidation: +23% for English; Chinese remains dominated by pool-read volume from beam churn, not per-probe cost.
Discussions
State-space models, the generic learning system
The state-space framing suggests this parser is a special case of something more general. Where a state space is too immense to tabulate, possibly due to the hierarchical nature of the real world, the classical approach becomes fundamentally intractable. Hypervectors sidestep this because a hierarchical state keeps the same fixed width as a flat one, with simple and intuitive bookkeeping from this package.
Commercial support
All code in the hv repository — Python source, examples, and documentation — is released under the MIT License and is free to use, including in commercial products. The underlying engine, shipped as a compiled extension in the published wheel, is proprietary. Nothing on this page is required in order to use the library.
Consulting and support agreements
For work with a defined scope and a contract — as distinct from sponsorship — the usual engagements are:
- Integration — applying hypervector representations to your data, or embedding the library into an existing system.
- Training and knowledge transfer — walkthroughs of the substrate, the dependency parser, and how to read a decode.
- Feature development — prioritised work on the library itself, upstreamed under the project’s existing licensing unless agreed otherwise.
- Support agreement — a defined response time for issues affecting you.
To start a conversation, use the contact form and mention the scope and timeline you have in mind.
Supporting the project
If you simply want the library maintained rather than a contract, sponsorship goes toward maintenance, documentation, and keeping the Rust, Go, and Python implementations at parity:
- Buy Me a Coffee — one-off or monthly.
- GitHub Sponsors — recurring, billed through your existing GitHub account, and able to invoice an organization rather than charge a card.
Sponsorship carries no SLA and no commitment to implement particular features; that is what the consulting route above is for.
Full terms, and the list of current sponsors, are in SPONSORS.md in the repository.