Hyperplane.NET
0.1.26
dotnet add package Hyperplane.NET --version 0.1.26
NuGet\Install-Package Hyperplane.NET -Version 0.1.26
<PackageReference Include="Hyperplane.NET" Version="0.1.26" />
<PackageVersion Include="Hyperplane.NET" Version="0.1.26" />
<PackageReference Include="Hyperplane.NET" />
paket add Hyperplane.NET --version 0.1.26
#r "nuget: Hyperplane.NET, 0.1.26"
#:package Hyperplane.NET@0.1.26
#addin nuget:?package=Hyperplane.NET&version=0.1.26
#tool nuget:?package=Hyperplane.NET&version=0.1.26
Hyperplane.NET
Core library of Hyperplane: Vector Decision Models for .NET, written in G# and ported from the ideas of Venn.
A frozen reader turns content into vectors once; Hyperplane answers typed questions over those vectors. The library is pure managed code with no native dependencies, and is NativeAOT compatible.
Main types
| Area | Types |
|---|---|
| Profiles | EmbedderProfile, VectorTag, Venn1, Profiles |
| Readers | IEmbedder, CachedEmbedder (content-addressed LRU + optional file cache), CoalescingEmbedder (opt-in batching), DeterministicEmbedder (tests) |
| Generic head | HeadBundle (Load, Resolve, Heuristic), HeadDownloader, CosineAbstentionHead, SafeTensors, PreparedQuestion, TemperatureCalibration |
| Decisions | DecisionService (native requests, indexes, prepared questions, calibrations, families), DecisionsApi (Decisions API translator), ContractError |
| Space operations | SpaceOps (nearest reference, set membership, population shift, counterfactual choice) |
| Outcomes | IOutcomeStore, InMemoryOutcomeStore, FileOutcomeStore, OutcomeService, OutcomeHeadFamily, EventHistory |
| Families | LinearChoiceFamily, PointwiseFamily, RegressionFamily, ResidualChoiceFamily, FamilyStore, FamilyFormats |
| Numerics | VectorMath, Prob, Linalg, Lbfgs, AdamW, Rng |
Getting a head
// Download venn-1 (pinned revision, SHA-256 verified) into the user cache, then load it.
let directory = HeadDownloader.DownloadAsync().Result
let bundle = HeadBundle.Load(directory)
// Or: use HYPERPLANE_HEAD_DIR when set, else the uncalibrated heuristic head.
let resolved = HeadBundle.Resolve()
let service = DecisionService(bundle)
Console.WriteLine(service.HeadDirectory)
Console.WriteLine(service.HeadConfigSha256)
Console.WriteLine(service.HeadWeightsSha256)
For reproducible deployments prefer HeadBundle.Load(directory) with an explicitly chosen directory;
Resolve(directory) also loads that directory, while Resolve() consults the environment and falls back
to the heuristic unless allowHeuristic: false. Neither discovers the default cache automatically.
The service properties identify the generic inference head snapshot: the absolute, normalized load
directory (not symlink-resolved), and lowercase SHA-256 values of the exact verified config and weights bytes.
Both artifacts must appear in the manifest; all listed artifacts are checked. The manifest is not a trusted
signature or a pin: compare both digests with independently trusted values, or use HeadDownloader for its
published pins. The paths and hashes are not included in API responses or persisted; log them explicitly if
appropriate, taking care with local path disclosure. They do not identify a fitted family scorer or prove
which scorer answered; inspect scorer_type and scorer_identity for that.
All three properties are null for heuristic or manually constructed bundles, and when the loaded head was modified before service construction. A service snapshots its head and provenance at construction, so later mutations or file changes do not change them. Copying a head into a new manually constructed bundle does not transfer provenance; on restart load the head again.
The head is tied to the venn-1 profile (EmbeddingGemma 2, 768 dimensions, Classification prompt).
Vectors from any other reader must use an experimental: profile and a fitted family or the heuristic head.
Deciding
DecisionService.Decide takes Venn's native request: a state (a vector, {"vectors": [...]}, an
index_ref, or text when a reader is configured) and named questions of type Choice, Score, Noul,
IndexApply, NearestReference, SetMembership or PopulationShift. Options are labeled vectors and the
question is an instructions_vec. DecisionsApi.Decide(service, request) accepts the Decisions API wire
format (model, state, questions of choice/score/noul with text criteria) and needs a reader.
Option-scored answers report scorer_type: "family" | "generic" and scorer_identity (native answer fields,
including each IndexApply row; Decisions API hyperplane and venn metadata). family_identity describes
the requested registered family even when the generic scorer actually answers. A residual family with
k2_fallback enabled uses the generic scorer for exactly two options; unregistered names also use it.
Set the optional boolean require_family_scorer: true on an option-scored question to reject generic
scoring with 422 / scorer_unavailable, including residual K=2 fallback and missing families. The default
is false; a non-boolean gives 422 / scorer_requirement. The control also works on IndexApply and
Decisions API option questions, and may be supplied or overridden on a question_ref without re-registering.
It is a scoring requirement, not a calibration guarantee; identities and calibration selection remain
unchanged. Replacing or deleting a family rebinds registered questions even if they require its scorer;
subsequent strict requests fail if the new binding is generic. It does not apply to regression or geometry questions.
Diagnostics
Pass an optional Action<DecisionDiagnostic> as diagnostics to DecisionService (no logging dependency):
var service = new DecisionService(diagnostics: e =>
Console.WriteLine($"{e.Kind} {e.Status} {e.FamilyKey} {e.ScorerIdentity}"));
Events have Kind, Status, nullable FamilyKey, FamilyIdentity, and ScorerIdentity. FamilyKey
is SHA-256 of the UTF-8 family name (including the empty name); it is an identifier, not anonymization
against dictionary attacks. Built-in family and built-in or generic scorer identities match the digests
reported in answers. Event identifiers only retain 64-character hexadecimal values, normalized to lowercase;
other custom family or scorer identities become null, without changing answer metadata. Hexadecimal shape
does not prove an identity is a genuine digest. The head event's ScorerIdentity instead
identifies the generic configuration, not a particular served scorer. Digests are lowercase and deterministic.
Events never include names, paths, input text, labels, vectors, exception messages or calibration data.
| Kind | Status and timing |
|---|---|
head |
heuristic, verified, or unverified; after the constructor publishes its snapshot. The hook observes the supplied/resolved bundle, not earlier HeadBundle loading failures. |
family_load |
loaded, quarantined, invalid (quarantine failed), incompatible, or unavailable; after startup publication. Failed manifests use the manifest basename as key if it is a SHA-256, otherwise its SHA-256. |
calibration_load |
absent, loaded, quarantined, or invalid (quarantine failed); after startup publication. loaded does not mean applicable to a particular answer. |
family_change |
committed or deleted, after successful publication. |
calibration_change |
installed or deleted, after successful publication; an installed scoped artifact may still be inapplicable or uncalibrated. |
calibration |
active if the served answer's calibrated flag is true, otherwise inactive; once per option-scored question with at least one row. |
scorer_fallback |
k2 for a registered choice family with K=2 fallback, family_missing for an unregistered nonempty name, otherwise generic when a registered family actually served a generic scorer; accompanies calibration. The default unnamed generic scorer is not a fallback event. |
Decision events are delivered only after a successful complete Decide response, not during preparation,
registration, rejected strict requests or failed decisions. A stream emits events once per enumeration, after
its first batch is computed and before it is yielded; empty, unenumerated, or failed-before-first-batch
streams emit none. Later cancellation/failure does not retract events. Scorer and calibration fields refer
to the captured snapshot and first row (all rows in that stream share its input tag). Regression, geometry,
and outcome decisions do not produce these events. Legacy stderr warnings remain unchanged.
Callbacks are synchronous, may run concurrently, and must be fast and thread-safe. They run outside service
locks and writer leases, after publication or successful scoring; concurrent publications can make the current
registry newer than an event. There is no global ordering. Callbacks may reenter the service; diagnostics
generated inside the callback's execution context are suppressed to prevent recursion (including context
flow to child tasks). Callback Exceptions are swallowed; callbacks must not rely on delivery or throw to
control decisions. A null hook emits nothing and avoids per-row diagnostic work; no queue, background thread,
or retries are created. Recompile existing binaries when upgrading to the new constructor signature.
PopulationShift and SetMembership are capped at 512 state rows even for index_ref states
(413 / space_rows); population shift allows 512 rows in each population. Bandwidth must be positive
and finite. NearestReference scores references once and sorts evidence (not quadratic), retaining the
index's 1,000,000-row limit.
Inline regression responses also stop at 512 rows before scoring; use /index-apply for larger responses
(413 / stream_required).
Ranking new candidates as rows
Represent each (context, candidate) in the state vector, using the same reader or feature construction
and preprocessing used for the task. Ask the same fixed Choice question of each row with IndexApply;
sort the rows yourself by one chosen option's probabilities entry. Candidate IDs are not Choice options.
For a fitted single-vector Choice family, the question's option labels and vectors must be registered with
that family (a subset is allowed); the candidate state vectors may be new. A multi-field family cannot
consume these single-vector rows. An unregistered family name uses the generic head, so inspect
scorer_type when a fitted scorer is required.
This runnable vector-native example uses the uncalibrated heuristic, not a trained quality model. The hand-authored vectors are only a deterministic illustration, not embeddings or evidence of useful ranking:
import Hyperplane
import System
import System.Collections.Generic
import System.Linq
import System.Text.Json.Nodes
let profile = EmbedderProfile("experimental:demo", "demo-reader", "0123456789abcdef0123456789abcdef01234567", 4, "Classification")
let service = DecisionService(HeadBundle.Heuristic(4), nil, nil, profile)
let vectors = Js.Parse("[[0,1,0,0],[1,0,0,0],[1,1,0,0],[2,0,0,0]]")
let ids = Js.Parse("[\"weak\",\"strong\",\"middle\",\"strong-tie\"]")
let question = Js.Parse("{\"type\":\"IndexApply\",\"instructions_vec\":[0.5,0.5,0.5,0.5],"
+ "\"options\":[{\"label\":\"accept\",\"vector\":[1,0,0,0]},"
+ "{\"label\":\"reject\",\"vector\":[0,1,0,0]}],\"batch_size\":2}")!!.AsObject()
let handle = service.RegisterIndex(vectors, ids)
let rows = List[JsonNode]()
for line in service.StreamIndex(handle, question) {
for row in Js.Parse(line)!!["rows"]!!.AsArray() {
rows.Add(row)
}
}
let ranked = rows.OrderByDescending(row -> Js.Num(row["probabilities"]!!["accept"])!!)
.ThenBy(row -> Js.Str(row["id"])!!, StringComparer.Ordinal).ToArray()
// IDs: strong, strong-tie, middle, weak. The first two tie after unit normalization.
The test CandidateRankingTests executes this example. In an application, replace the toy service and
vectors with a task-appropriate model and candidate representations; for a fitted family, add "family" and
use its registered options and compatible vector tag. The same question can be used with Decide and a
plural state ({"vectors":[...]}), or {"index_ref":"<handle>"}. Inline plural rows have numeric
zero-based IDs; index-backed and streamed rows carry the supplied distinct IDs. Inline states accept up
to 512 rows; inline IndexApply rejects a requested row_cap above 512, even for an index. RegisterIndex
accepts up to 1,000,000 rows, and StreamIndex emits NDJSON {offset, rows} batches in input order,
up to row_cap (default: all indexed rows). It does not sort. For large sets, process batches or maintain
a top-k heap instead of collecting every row as above. Pass a CancellationToken to RegisterIndex,
Decide or StreamIndex; the stream checks it during enumeration. The server equivalent is /index-apply.
These are per-row choice probabilities, not a probability distribution over candidates: each softmax
normalizes that row's requested options and none, using the resolved scorer's temperature. They
need not sum to one across rows. The example sorts accept, not confidence (the largest probability
over all options and none), a raw logit, or Score's expected rubric score. answer is the maximum
including none; an optional threshold changes it to none when that maximum is below the threshold,
without changing probabilities or confidence. Decide explicitly whether to exclude abstaining rows before
ranking; the example retains them. Linear families use a fixed, effectively non-winning none logit,
whereas other scorers may select none.
The generic head reports calibrated: false unless a matching scoped artifact passes its report criteria;
family calibration flags require matching fitted inputs, while an uncalibrated generic fallback reports false. Neither that flag nor
per-row normalization establishes calibrated ranking probabilities, a posterior over this candidate set,
or performance on new candidates. Choice probabilities also depend on the requested option set and
scorer/temperature: keep them consistent across rows, and evaluate ranking and any calibration on held-out
data from the intended task. For changing candidates conditioned on a context, use the pointwise family below.
Pointwise ranking of unseen candidates
Register a family with objective: "pointwise" and form: "linear" (the default). Each numeric
example is {"context": [...], "candidate": [...], "outcome": 0|1, "group_id": "..."}. Outcomes
describe whether that candidate passes for that context. Group IDs must be nonempty strings; use the
same ID for related observations. Context and candidate vectors use the same service profile, revision
and dimensions. A features tag can be supplied on the family and must match the candidate state tag.
All vectors are unit-normalized, including features, so magnitude is not preserved.
For example, after creating a four-dimensional DecisionService named service:
let examples = JsonArray()
for g in 0 ... 30 {
for label in 0 ... 2 {
let row = JsonObject()
row["context"] = Js.FromVector([]float32{1, float32(g) * 0.01f, 0.3f, 0.4f})
row["candidate"] = Js.FromVector([]float32{1, if label == 1 { 1.0f } else { -1.0f }, float32(g) * 0.01f, 0.25f})
row["outcome"] = label
row["group_id"] = "group-$g"
Js.Add(examples, row)
}
}
let body = JsonObject()
body["objective"] = "pointwise"
body["examples"] = examples
let report = service.RegisterFamily("quality", body)
let request = JsonObject()
request["state"] = Js.Parse("[[1,-1,0.31,0.25],[1,1,0.32,0.25]]")
request["questions"] = Js.Parse("{\"ranking\":{\"type\":\"Rank\",\"family\":\"quality\","
+ "\"context\":[1,0.31,0.3,0.4],\"ids\":[\"candidate-a\",\"candidate-b\"]}}")
let ranking = service.Decide(request)["answers"]!!["ranking"]!!
This toy example illustrates the API, not evidence of useful or calibrated predictions. Rank accepts
1–512 candidate vectors and requires distinct nonempty string IDs; index-backed candidates use their
registered IDs instead. It rejects missing/wrong families, text inputs, duplicate IDs and unsupported
question fields. Results are ordered by descending per-row probability (estimated P(outcome=1)),
breaking ties by ordinal ID. Duplicate vectors are allowed with distinct IDs. There is no none option
or implicit abstention: callers decide whether any candidate is acceptable. rank_weight divides the
pointwise probabilities by their sum (uniform if all underflow to zero); it is a ranking convenience,
not a posterior and does not model mutual exclusivity. Rank is available through Decide and the
server decision route with lowercase "type":"rank" and a state object {"vectors":[...]} (or
{"index_ref":"..."}). Rank questions cannot be pre-registered or used on the streaming /index-apply
route; index rows are limited to 512 for Rank. This new pointwise model is independent of the Venn head;
no Venn model parity is claimed.
The model is regularized binary logistic regression over normalized context, candidate, and their
coordinatewise products. It selects among three regularization strengths by three-fold grouped
cross-validation on the training partition, or uses fixed C=1 when those folds cannot each contain both
classes. The deterministic train/calibration/report split groups connected observations sharing a
normalized context, normalized candidate, or group_id, including groups with mixed outcomes; connected
components never cross partitions or CV folds. If fewer than three independent components remain, or
training has fewer than two rows of either class, fitting fails. The calibration partition fits a temperature
only with at least five examples from five independent components of each class and informative scores.
The untouched report partition evaluates positive probability calibration using 15-bin ECE and a 95%
bootstrap interval resampling whole connected
components. calibrated is true only when temperature fitting succeeded, report has at least five of
each outcome from five independent components per class, 20 independent components overall, the configured
minimum row count (default 500), and its upper ECE interval meets the configured error bar (default 0.05).
These are empirical criteria, not a guarantee under distribution shift or within subgroups; a lax configured
error bar is not strong evidence. Labels and grouping must reflect the intended deployment population
and all sources of dependence. A false flag
means the returned probabilities have not passed these criteria. Identity, training and split digests,
and weight checksums are persisted with the family.
Inline prepared scorers have a 1024-entry cache with simple capacity eviction. Registered question_ref
handles are stored separately and survive cache eviction. PreparedCount reports cache residency;
PrewarmCount is the cumulative number of constructed scorers, including rebuilds after eviction.
For repeated decisions over a single untagged vector and a registered question, use
service.Decide(state, questionRef, cancellationToken) with a float[]/[]float32. It returns the same
response as a JSON request with that vector and a question named q; the state must have the service's
dimension, finite coordinates and nonzero norm. It is copied and cannot represent tagged features, text,
multiple states or question overrides; use the JSON API for those.
Each registry generation also retains up to four small resolved question plans. Inline Choice plans are
matched by content, not object identity, so sequential mutations are detected; questions requiring
embedding, custom families, large questions and unsupported shapes follow the normal path. Registered
references can also use this cache. It is bounded by four entries, 32,768 JSON nodes and 131,072 string,
key and parsed-number characters per retained tree, with a maximum depth of 64; request-level family names
over 131,072 characters are not cached. Comparisons use immutable plan snapshots without holding the
prepared-scorer gate. Publishing a new registry generation discards these plans. Do not mutate a JSON request
or state array concurrently with a decision.
Embedding, scorer binding and fitting run outside registry locks. Each Decide or StreamIndex captures one
registry generation, including families, question handles, calibrations and indexes; in-flight work can finish
against that generation after a replacement or deletion. A stream retains its generation when enumerated.
Index(handle) returns detached vectors, IDs, outcomes and tag. Reader calls are serialized separately to
support readers that are not thread-safe. Custom families remain caller-owned: their Bind calls are serialized
per instance, but their scorers and regression answers must support concurrent calls. Inputs passed to custom
scorers are detached from registry-owned index rows.
Text inputs contain 1..32768 UTF-16 code units (text_length). Every embedder's outputs are checked for row
count, dimensions, finite coordinates and nonzero norm before use or publication.
CachedEmbedder looks up each cached key once per batch, reusing its vector-and-info pair for duplicates,
and deduplicates misses. Later batches can observe cache updates from other instances. It forwards its async
path to the inner EmbedAsync; Misses counts unique backend rows and Hits includes reuse within a batch.
Readers whose frozen configuration can become invalid can implement IReaderValidation.ValidateReader.
CachedEmbedder checks validity before/after reads, including cache hits, and forwards it through nested
caches. CoalescingEmbedder forwards validation through its serial worker and before returning results.
Custom wrappers must forward this optional contract; validation must be thread-safe and must not perform embedding.
Coalescing concurrent text reads
CoalescingEmbedder is opt-in. A single wrapper combines concurrent reads into ordered batches on one
dedicated worker, and DecisionService admits concurrent calls to this wrapper instead of taking its usual
reader lock. The inner reader still runs serially. For example, replace the deterministic reader with an
actual configured reader:
using Hyperplane;
using System.Text.Json.Nodes;
var inner = new DeterministicEmbedder(2); // demonstration only
using var reader = new CoalescingEmbedder(inner, maximumBatchSize: 4, queueCapacity: 32, delayMilliseconds: 5);
var service = new DecisionService(HeadBundle.Heuristic(2), reader);
var question = JsonNode.Parse("""{"instructions_vec":[1,1],"options":[{"label":"a","vector":[1,0]},{"label":"b","vector":[0,1]}]}""")!.AsObject();
var handle = service.RegisterQuestion(question);
JsonNode Request(string text) => new JsonObject {
["state"] = text,
["questions"] = new JsonObject { ["q"] = new JsonObject { ["question_ref"] = handle } }
};
var results = await Task.WhenAll(Task.Run(() => service.Decide(Request("one"))),
Task.Run(() => service.Decide(Request("two"))));
Only one live wrapper may own a given reader. Route all concurrent access through that wrapper, including
across services; wrapping the same underlying backend indirectly or calling it directly bypasses this
protection. The wrapper does not own the inner reader: dispose the wrapper before disposing the reader.
Profile, prompt, reader identity, row order and per-row information come from that one reader; it does not
make different reader configurations equivalent. Requests larger than maximumBatchSize are split in order.
The bounded queue holds at most queueCapacity chunks, each at most maximumBatchSize rows; callers waiting
for space retain their own inputs/results. The delay (0..1000 ms) is the maximum collection window after the
worker starts a batch, not a bound on total queue or reader latency. Choose limits compatible with the
backend's token/context limits; a combined batch can fail where smaller separate calls succeed.
Sync and async callers can mix. A canceled waiter stops waiting independently. At dispatch, each collected request is checked for cancellation and canceled requests are omitted; cancellation racing with or after that check may still reach the reader. Shared work already selected continues for other waiters. A reader failure is delivered to every request in that batch; subsequent batches can continue. Disposing rejects queued/new work and requests cooperative cancellation of active work, then waits for the worker; an uncooperative reader can delay disposal. The wrapper uses the inner synchronous methods on its worker even for async callers. There is no guarantee batching improves performance: measure with your reader, concurrency and text sizes. See benchmarks.
Host-built feature vectors
Numerical decision-time features can be sent without a reader. Register a profile of the appropriate dimension
and construct a complete VectorTag with representation features. For example, with a registered
three-dimensional profile p, use VectorTag(p.Id, p.Revision, "features", 3, ["flag", "count", "ms"]).
The profile/revision/dimension must match the service; fields and their order distinguish feature schemas.
For example:
{"vector":[1,1000,25],"tag":{"profile":"my-profile","revision":"v1","representation":"features","dimensions":3,"fields":["flag","count","ms"]}}
In RegisterFamily, put that complete tag in the top-level "tag" and supply numeric example states
(arrays or tagged vector objects). Choice supports linear and residual; regression supports ridge and
kernel_ridge, including tagged indexes or matching outcome-store partitions as sources. Text-only regression
inputs are not supported for features. For Decide, send a tagged state as above, or
{"vectors":[...],"tag":{...}} for plural/IndexApply; RegisterIndex accepts the same plural object and
retains its tag for index decisions and streams. A feature family requires the identical tag at serving, and
a non-feature family cannot consume a tagged feature state. Tags are included in family identity and retained
on reload; the fitted embedding_profile records the service configuration, not proof that a reader
created host vectors. Callers must preserve their feature schema and preprocessing across training and serving.
On the server, POST /indexes puts that plural object inside the outer "vectors" field:
{"vectors":{"vectors":[...],"tag":{...}},"ids":[...]}.
Registered index tags, built-in outcome-store tags, and registered outcome-family tags are detached from
caller-owned tags. Reading Index(handle).Tag, StateValue.Tag, a built-in store's Tag, or a registered
outcome family's Tag gives a detached tag: changing its Fields does not relabel registered data.
This isolation covers tags, not the other mutable arrays exposed by these APIs. App-owned adapters remain
responsible for their own tag ownership.
Built-in Choice and regression families, the generic head, and indexes project nonzero states to unit
length, including features. Exactly zero feature rows stay zero; nonzero feature rows with norm at most
1e-12 are rejected by DecisionService to avoid inconsistent repeated normalization. Other representations
still reject zero rows. No per-feature means/scales are learned or saved: callers must fit and persist any
standardization themselves and apply it identically at serving. For instance [1,1000,25] is dominated by
the count even after unit projection; absolute magnitude is discarded. The choice head still expects
same-dimensional question and option vectors in its own embedding space: a pretrained text head has no
guaranteed meaning on arbitrary features, especially residual or generic fallback scoring. Use validated
models and evaluate held-out data; a tag is a caller assertion, not a learned alignment.
Outcome stores differ: their built-in squared-L2 search uses the supplied coordinates without unit normalization, and compiled outcome heads train and score on those coordinates. Both accept zero features and enforce matching tags; the file store and outcome heads retain tags on reload. Outcome-head training converts stored coordinates to float16 keys, so large or tiny values can overflow or lose precision. Geometric questions have their own operations (some normalize, some use raw distances); do not assume one common preprocessing policy across them. Feature tags on states, indexes and explicit geometry inputs must match. The Venn/OpenAI text facade and direct low-level numeric APIs do not infer feature tags or standardize data; use the native tagged paths above and manage validation/preprocessing in the host for direct calls.
Cancellation
Optional trailing CancellationToken parameters preserve existing calls on DecisionService embedding,
vector/index/question/calibration registration, decisions, family training/commit/delete, and index streams;
DecisionsApi.Decide, OutcomeService.RegisterFamily/DecideBatch, family Fit methods, space operations,
temperature fitting, L-BFGS and dense solves also accept tokens.
Tokens flow through nested helpers, parallel CV workers, epochs, batches and optimizer/line-search iterations.
Outcome training also checks during builtin neighbor search/sorting, post-search evidence aggregation and
pooled-baseline selection, rather than only between search batches. Distance ties retain insertion order.
Cancellation throws OperationCanceledException, including while waiting for the reader or store locks.
Stream tokens remain effective during enumeration, without leaking cancellation into unrelated caller work.
Training and weight staging precede publication. A canceled or failed stage is cleaned up and leaves the old
manifest, family and registered questions unchanged. The manifest switch and registry update are one short
commit: if that switch wins a cancellation race, publication finishes normally. Durable outcome appends
likewise finish their disk-and-memory publication once begun rather than leaving a half-append.
App-owned adapters can override IRegressionFamily.AnswersWithCancellation and
IOutcomeStore.SearchWithCancellation/ExportWithCancellation. Their defaults preserve existing adapters
and check before/after calls; custom blocking work must cooperate with the supplied token to stop promptly.
Outcome stores
Register an IOutcomeStore with service.Outcomes.RegisterStore(store), then call
service.DecideBatch(states, questions) with nearest_outcome questions to get per-option means, counts,
spreads and evidence IDs from the nearest historical cases, with min_support, goal (max/min) and
epsilon-greedy propensities. Write outcomes back with IWritableOutcomeStore.Add.
The optional Venn offpolicy.estimate_logged_policy IPS/SNIPS/ESS evaluator is not implemented.
FileOutcomeStore.Add validates and durably flushes both vector and case appends before publishing
to memory after both streams close successfully. Failed writes leave memory unchanged. Incomplete rollback
or stream-disposal failures disable further writes until reopen. Combined errors retain the original append
failure first, followed by rollback errors and then disposal errors; both streams are always offered cleanup.
A close failure after durable flush can leave a complete but unacknowledged case that survives reopening.
On reopen, recovery retains complete newline-terminated
JSON cases with complete corresponding vector rows, truncates unmatched trailing data (including partial
JSON lines and partial vector rows), and repairs inconsistent files before accepting appends. Healthy existing
stores, including legacy empty stores with only store.json, open without creating, rewriting or truncating
data files, so read/search does not require write access;
creating stores, appending and torn-write recovery still require the appropriate write permissions. A crash before the
first case record simply recovers an empty store. Use only one writer instance/process per directory.
Families
service.RegisterFamily(name, body) trains, persists (when the service has a home) and switches in a family:
- Choice:
{"form": "residual" | "linear", "examples": [{"state": [...], "label": "a", "group_id"?: "g", "weight"?: 1.0}], "options": [{"label": "a", "vector": [...]}], "instructions_vec": [...], "seed"?, "split"?, "cv"?, "class_weight"?} - Regression:
{"objective": "regress", "examples": [{"state": [...], "price": 12.5}], "target": "price"}, or{"objective": "regress", "from_store": "<index or outcome-store handle>", "target"?: "<partition>"}, with optional"form": "ridge" | "kernel_ridge","alphas","cv".
Choice examples accept positive finite weight (default 1). Before fitting, identical raw vectors with the
same label, original text and group are merged in first-occurrence order by summing weights. Thus two unit
copies and one weight-2 row give the same fit and training identity, including with class_weight. Balanced
class weights use the total example weight per label across the entire request, including held-out or
excluded rows (as with the existing class-balancing behavior); explicit class weights multiply example weights.
Use externally specified class weights if held-out labels must not influence balancing.
Input and effective weight totals are each capped at 100,000,000. The 10..100,000 input-row limit remains;
linear fitting also requires at least 10 merged rows and five distinct normalized states per label. Both forms
require at least two training rows per observed label. Weight does not increase these minimums.
Repeated normalized states with different labels, text, raw vector magnitudes or groups remain separate
observations. They and caller groups are linked into cross-validation components to prevent state or group
leakage; an explicit split uses original row indices and must keep identical states in one slice (including
excluded rows) and groups in one included slice. This can reduce the usable number of CV folds. Calibration
temperature and reported accuracy/ECE are unweighted over merged observations (residual uses sampled episodes),
so weights affect fitting and CV loss, not the amount of calibration evidence. Raw rows and effective weights
enter training_sha256 after merging; split hashes use merged row indices. Floating-point weight summation is
order-dependent. Direct Fit callers must supply the same group for repeated states; unlike registration,
direct fits do not coalesce rows. Unknown example fields are rejected; regression does not support example weights.
Duplicate and state lookup stores row-index metadata rather than serialized vector keys; it compares the
underlying vectors on hash collisions. Registration still retains raw and normalized vectors while fitting.
Choice fits accept max_degree_of_parallelism in the registration body, or
fitOptions: FitOptions(2) in LinearChoiceFamily.Fit and ResidualChoiceFamily.Fit.
Use a positive integer to cap each parallel fit loop, or -1 (the default) for the runtime default.
Regression and outcome-head fits currently run sequentially.
Regression limits apply both to RegressionFamily.Fit and to request registration:
- Ridge: 10..1,000,000 examples; kernel ridge: 10..512 examples (including store-backed training), with
413 / family_examplesfor an oversized kernel fit. - CV folds: integer 2..20; repeats: integer 1..10. Invalid/fractional values return
422 / family_cv, never silently fall back to defaults. - Each alpha/gamma/input-scale grid: 1..32 finite positive values, with at most 256 combined settings
(
422 / family_grid). Request registration and the library acceptalphas,gammasandscales; gamma applies to kernel ridge and scale applies to extra input features. - Combined CV budget:
settings × folds × repeats <= 1024fits andsettings × repeats × examples <= 32,000,000prediction cells (413 / family_cv). Defaults are unchanged; larger explicit configurations must reduce another dimension of the budget.
Questions then name the family ("family": "<name>"). Compiled outcome heads are trained with
service.Outcomes.RegisterFamily(name, fromStore, options, ...).
Outcome-head registration accepts 1..256 options; single-option fitting has valid zero cross entropy.
With a service home, calibrations use same-directory temporary files and atomic replacement. Invalid
calibration files and individual family manifests/weights are ignored on startup, with diagnostics on
stderr and the original manifest/file renamed to a unique *.invalid path when possible (otherwise
preserved in place). Transient family I/O/permission failures instead leave the manifest unchanged and skip
that family for this startup, allowing a later startup to retry it. Incompatible reader profiles, revisions
or dimensions, unavailable registered profiles/custom loaders, and missing or incompatible legacy residual
fallback heads likewise preserve the manifest for a later compatible startup. Stored residual heads remain
self-contained. Custom loaders should throw FamilyCompatibilityException for configuration mismatches
and InvalidDataException for confirmed corruption; a generic ContractError alone does not trigger quarantine.
Healthy families still load.
Built-in registered families expose a deterministic Identity, training digest and split hashes; answer
metadata identifies both the family and the actual scorer, including generic fallback. Legacy families remain
usable with unknown training provenance; custom families do not acquire one automatically. New service-fitted
families bind the reader and prompt; older identities without that binding remain usable but cannot verify them.
Native family-backed
Noul scorer identity also includes its effective generic choice temperature. The in-memory FamilyHistory
exposes verifiable event links for current fitted families and reconstructs them on reload.
Scoped calibration records are bound to model, scorer, question, options and input tag. Unbound legacy
temperatures are ignored by default. See
family identity and lineage
for the canonical format and its limits.
The service snapshots its generic head at construction and built-in families on registration. Family(name)
returns a detached copy; edit it and call CommitFamily to publish changes. Changing model parameters removes
the old training-provenance claim. RegressionAnswers scores caller-owned built-in regression families using
a detached snapshot, stripping stale provenance from that snapshot without modifying the caller's family.
Registered decisions retain their cached fast path. Create a new service to use an edited generic head. Custom
families remain caller-owned. Do not mutate inputs concurrently with snapshotting.
To measure decision latency, allocations and four-worker throughput with a real head, run
dotnet run -c Release --project test/Hyperplane.ServerConcurrency -- --identity-benchmark "$HYPERPLANE_VENN1_DIR".
For a reproducible headless 1-vs-4-worker comparison, run
dotnet run -c Release --project bench/Hyperplane.Bench -- --suite concurrency --dims 768 --hidden 512 --options 8 --rows 512 --warmup 2 --iterations 5.
This measures 512 prepared Choice decisions on one service using separate requests and a synthetic nonzero
MLP head; worker startup is included. On an Intel i7-13800H (20 logical CPUs), Ubuntu 26.04.1, .NET 10.0.15,
the mean was 523.846 ms (977.4 decisions/s) with one worker and 178.406 ms (2,869.9 decisions/s, 2.94×)
with four. The numbers are workload- and machine-dependent, not a speed guarantee.
Previously quarantined manifests are not automatically reinstated; validate them before restoring their
original .json names.
Family deletion removes disk state before the registry.
Weight staging, question rebinding and calibration serialization occur outside the registry lock; only the
atomic file switch and corresponding registry publication hold it. Concurrent question registration causes
rebinding to retry before publication, never a partially switched generation.
Use one live DecisionService per home: writer locks and in-memory registries are instance-local.
Standalone FamilyStore callers must externally serialize access to a directory, including across instances;
it provides atomic file replacement, not shared-directory transactions or registry synchronization.
Outcome-head digests now use Venn/PyTorch order: float32 bias, left.weight, right.weight. New assets mark
digest_algorithm: "venn-state-dict-f32-v1" and verify that digest. Unmarked Hyperplane 0.1.3 assets still
verify against their original left/right/bias digest and load without modification; resaving writes the
canonical digest. Sha256 reports the canonical digest even after loading a legacy asset.
Only a missing digest_algorithm permits legacy verification; explicit null, non-string or unknown markers
are rejected, even when the checksum otherwise matches.
See the repository's DESIGN.md for the math.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Hyperplane.NET:
| Package | Downloads |
|---|---|
|
Hyperplane.Cider
Optional reader adapter for Hyperplane.NET: CiderEmbedder turns any Cider.NET IEmbeddingBackend (including Cider.Native's in-process llama.cpp LlamaEmbedder over GGUF models) into a Hyperplane IEmbedder with an honest, provenance-derived experimental profile. |
GitHub repositories
This package is not used by any popular GitHub repositories.