Shared Encoder API¶
One LoRA-adapted backbone reads marked fields and queries. Fusion combines the present code
channels, then one affine projection feeds the arm's geometry head. The hyperbolic head uses
r = R * tanh(norm(v) / R) at unit curvature; it has no curvature parameter. The Euclidean and
spherical heads take v and its direction as they are (Req 12).
Fields and Markers¶
The text fields the shared encoder reads, and their markers (Req 14; spec R13).
A code has four channels: title, description, excluded and examples. A query is a fifth field. A
present text is marked with its field's name, '<field>: <text>', so one backbone can tell the
fields apart. An absent text (null or blank) is the empty string with present False and no
marker, so fusion can mask it (Req 9).
marked_text(field, text)
¶
A present text with its field's marker, '<field>: <text>'.
marker(field)
¶
The prefix that marks a field's text.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the field is outside the marker set. |
tokenize_field(tokenizer, field, text, max_length)
¶
Tokenize one field text as the tokenization cache stores it.
A present text is tokenized with its marker. An absent one (null or blank) is the empty
string, [CLS] [SEP], with present False and no marker. Either is truncated and padded
to max_length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
Any
|
The backbone's tokenizer. |
required |
field
|
str
|
One of |
required |
text
|
Optional[str]
|
The field's text; None or blank is absent. |
required |
max_length
|
int
|
Tokens kept, at most the backbone's trained window. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the field is outside the marker set. |
Fusion¶
Fusion of a code's channel vectors into one vector (Req 14; Req 9; spec 4.1).
Every option reads only the present channels: an absent channel's slot is masked whatever it holds, and a row with no present channel fuses to a finite vector with a finite gradient.
masked_mean, the default: the sum over present channels, divided by max(1, number present).attention: a learned vector scores each present channel by its dot product, and a softmax over the present channels weights them.moe, an ablation only (R12): the masked mean, then the mixture of experts on that vector. Only this option emits gate probabilities and expert indices.
AttentionFusion
¶
Bases: Module
Attention pooling over the present channels.
The learned vector starts at zeros, so the pooling starts as the masked mean. Absent slots are zeroed first, so what they hold reaches neither the scores nor their gradient. An absent channel then scores the dtype's minimum and its weight is zeroed, so a row with no present channel has zero weights, a zero vector and a finite gradient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hidden_size
|
int
|
The width of the channel vectors. |
required |
FusionOutput
dataclass
¶
One fused vector per row, with the experts' gates under moe only.
MaskedMeanFusion
¶
Bases: Module
The default fusion. It has no parameters, so no absent channel can contribute.
MoEFusion
¶
Bases: Module
The MoE ablation (R12): the masked mean, then the mixture of experts on the fused vector.
The experts belong to the fusion step; the load-balancing term reads their gates (R11).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hidden_size
|
int
|
The width of the channel vectors, the experts' input and output. |
required |
num_experts
|
int
|
The number of experts. |
4
|
top_k
|
int
|
The experts each row is routed to. |
2
|
hidden_dim
|
int
|
The experts' hidden width. |
1024
|
build_fusion(name, hidden_size, *, num_experts=4, top_k=2, moe_hidden_dim=1024)
¶
The fusion module that model.fusion names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
One of |
required |
hidden_size
|
int
|
The width of the channel vectors. |
required |
num_experts
|
int
|
The number of experts, under |
4
|
top_k
|
int
|
The experts each row is routed to, under |
2
|
moe_hidden_dim
|
int
|
The experts' hidden width, under |
1024
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the name is outside |
masked_mean(vectors, present)
¶
The mean over present channels, (B, F, H) and (B, F) to (B, H).
A row with no present channel is zeros, divided by one, never by zero.
Geometry Heads¶
The geometry heads of Req 12's three arms: Euclidean, spherical and hyperbolic.
Every head takes the projection's output v (B, d) and returns HeadPoints:
tangent: the coordinates the export writes, Req 2's form of the arm. The hyperbolic head writes its bounded tangent r · û, the Euclidean head v and the spherical head û;embedding: the point the arm's decoding distance reads. It is the Lorentz point (B, d + 1) under hyperbolic andtangentitself otherwise;radiusanddirection: the polar parts that the code cache keeps and the training distance reads.
Each head also names its geometry and its decoding distance (a panels.decoding
DISTANCES name). radial says whether the radial term applies, which it does only in the
hyperbolic arm (Req 12). pair_distance is its training distance over polar parts, (A, B) in
the inputs' dtype. read_points maps exported coordinates to the float64 CPU points its
distance reads. The hyperbolic head is hyperbolic.HyperbolicHead; this module adds the two
flat heads and builds a head by name.
EuclideanHead
¶
Bases: Module
The Euclidean head (Req 12): the point is the projection's output v itself.
Its radius is r = ‖v‖ and its direction û = v / ‖v‖ (0 at v = 0): the polar parts the code
cache keeps. The training distance is ‖v_a − v_b‖ in polar form (flat_distance). The
export writes v, and a read takes it as it is, in float64. The head has no parameters and no
bound, so model.radius_bound is not read, and the radial term does not apply (P4).
forward(vectors)
¶
The point v, with its radius ‖v‖ and direction û, in the vectors' dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vectors
|
Tensor
|
The projection's outputs, (B, d). |
required |
Returns:
| Type | Description |
|---|---|
HeadPoints
|
v as both the tangent and the embedding, the radius and the direction. |
pair_distance(radius_a, direction_a, radius_b, direction_b)
staticmethod
¶
The training distance between two sets of the head's points: flat_distance.
read_points(tangent)
staticmethod
¶
Exported points as they are, float64 on the CPU.
SphericalHead
¶
Bases: Module
The spherical head (Req 12): the point is the direction û = v / ‖v‖ on the unit sphere.
Its radius is the constant 1, or 0 at v = 0, and takes no gradient: every point on the sphere
is at distance 1 from the origin, and the radial term does not apply. The training distance is
the chord form of the cosine distance (chord_distance). The export writes û, and a read
takes it as it is, in float64. It writes û rather than v because, under the cosine distance,
v's norm receives no training signal, so the regressor panel would read an untrained norm
(P5).
forward(vectors)
¶
The point û, with the constant radius 1 (0 at v = 0), in the vectors' dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vectors
|
Tensor
|
The projection's outputs, (B, d). |
required |
Returns:
| Type | Description |
|---|---|
HeadPoints
|
û as the tangent, the embedding and the direction, and the radius. |
pair_distance(radius_a, direction_a, radius_b, direction_b)
staticmethod
¶
The training distance between two sets of the head's points: chord_distance.
read_points(tangent)
staticmethod
¶
Exported directions as they are, float64 on the CPU.
build_head(geometry, *, radius_bound=8.0)
¶
The head of a geometry arm (model.geometry).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geometry
|
str
|
One of |
required |
radius_bound
|
float
|
R, read by the hyperbolic head only ( |
8.0
|
Returns:
| Type | Description |
|---|---|
Module
|
The head, with no parameters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the geometry is unknown, or as |
chord_distance(radius_a, direction_a, radius_b, direction_b)
¶
The cosine distance 1 − cos θ between every direction of one set and every direction of another, in chord form: ‖û_a − û_b‖² / 2.
For unit vectors the two are equal, and the chord form takes explicit differences, so it resolves small angles in float32, where 1 − û_a · û_b cancels. The radii are not read: on the sphere every point is at distance 1 from the origin. The gradient is finite everywhere, zero separation included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius_a
|
Tensor
|
The first set's radii, (A,); checked for shape only. |
required |
direction_a
|
Tensor
|
Its directions, (A, d). |
required |
radius_b
|
Tensor
|
The second set's radii, (B,); checked for shape only. |
required |
direction_b
|
Tensor
|
Its directions, (B, d). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
The distances, (A, B), in the inputs' dtype. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the shapes are not (A,), (A, d), (B,) and (B, d). |
flat_distance(radius_a, direction_a, radius_b, direction_b)
¶
The Euclidean distance ‖v_a − v_b‖ between every point of one set and every point of another, from each point's radius r = ‖v‖ and direction û.
The polar form is exact:
‖v_a − v_b‖ = √((r_a − r_b)² + r_a · r_b · ‖û_a − û_b‖²)
Every term is non-negative, so nothing cancels, and ‖û_a − û_b‖² comes from explicit
differences, as in polar_distance. The square root is guarded at zero, where an anchor
meets its own live row: the distance is 0, and the value and its gradient stay finite.
At v = 0 exactly, or where the float32 norm underflows, the polar form gives the point no
gradient, as polar_distance does for the hyperbolic head (P4).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius_a
|
Tensor
|
The first set's radii, (A,). |
required |
direction_a
|
Tensor
|
Its directions, (A, d): unit vectors, or 0 at the origin. |
required |
radius_b
|
Tensor
|
The second set's radii, (B,). |
required |
direction_b
|
Tensor
|
Its directions, (B, d). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
The distances, (A, B), in the inputs' dtype. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the shapes are not (A,), (A, d), (B,) and (B, d). |
head_of(model)
¶
A model's geometry head: the Lightning module's encoder's, or a shared encoder's own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The Lightning module, or its shared encoder. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
The head. |
Encoder¶
The shared encoder (Req 14; spec 4.1): one backbone with one LoRA adapter, for every field.
Per code the path is:
- field-marked channel texts;
- one backbone with one LoRA adapter;
- an attention-masked mean over each text's tokens;
- fusion over the present channels;
- one
Linear(hidden → d); - the geometry head, which gives the point.
A query is a one-field batch, {'query': …}, and takes the same path.
Each field's present texts go to the backbone in chunks of at most max_texts_per_call, each
trimmed to its own longest text. So no absent text, and no padding column beyond a chunk's longest
text, enters the backbone. Presence comes from each field's present flag, never from the
attention mask (Req 9).
Under autocast only the backbone runs in reduced precision. The pooled vectors are cast to float32, and fusion, the projection and the head run with autocast off (spec 4.2).
SharedEncoder
¶
Bases: Module
One LoRA-adapted backbone for every field, then fusion, one affine map and the head.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_model_name
|
str
|
The backbone's Hugging Face name. |
'sentence-transformers/all-MiniLM-L6-v2'
|
lora_r
|
int
|
LoRA rank. |
8
|
lora_alpha
|
int
|
LoRA scaling factor. |
16
|
lora_dropout
|
float
|
LoRA dropout rate. |
0.1
|
fusion
|
str
|
One of |
'masked_mean'
|
dimension
|
int
|
The embedding dimension, one of |
16
|
geometry
|
str
|
The geometry arm, one of |
'hyperbolic'
|
num_experts
|
int
|
The number of experts, under |
4
|
top_k
|
int
|
The experts each code is routed to, under |
2
|
moe_hidden_dim
|
int
|
The experts' hidden width, under |
1024
|
radius_bound
|
float
|
R, the hyperbolic head's bound on every radius ( |
8.0
|
use_gradient_checkpointing
|
bool
|
Recompute the backbone's activations in the backward pass. |
True
|
max_texts_per_call
|
int
|
The most texts one backbone call carries. It bounds a call's memory. With dropout off it leaves every output unchanged up to float noise; with dropout on it changes which random draws each text gets. |
MAX_TEXTS_PER_CALL
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the fusion, the dimension or the geometry is outside its set, or
|
forward(channel_inputs)
¶
Encode a batch of codes (the four channels) or of queries (the field query).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel_inputs
|
Mapping[str, Mapping[str, Tensor]]
|
Per field, |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Tensor]
|
|
Dict[str, Tensor]
|
hyperbolic, (B, d) otherwise; |
Dict[str, Tensor]
|
|
Dict[str, Tensor]
|
and |
Dict[str, Tensor]
|
autocast too. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the batch has no field, a field outside the marker set, or a field
without its |
load_base_model(name)
¶
The backbone's pretrained weights. Tests replace this with a one-layer BERT.