> ## Documentation Index
> Fetch the complete documentation index at: https://khaos-ml.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Model architectures

> Network definitions you can train and export as artifacts.

Khaos provides the network architectures for its artifacts, so your training code
and the serving runtime agree on the model. You train them however you like, then
export with one call.

```bash theme={null}
pip install "khaos-ml[train]"
```

## The workflow

```python theme={null}
import khaos.modeling as km
from khaos.export import export_artifact

model = km.build("tele_sensor_vibration")            # default architecture
model = km.build("tele_sensor_vibration", dim=256)   # override any setting

# ... train it with your own loop ...

export_artifact(model, "tele_sensor_vibration", "./my-artifact", version="v1")
# ./my-artifact/manifest.json
# ./my-artifact/model.onnx
```

`export_artifact` writes the manifest and ONNX file described in
[Bringing your own weights](https://khaos-ml.mintlify.site/usage/training-handoff.md), so `khaos serve ./my-artifact`
works straight away. Each domain also exposes its own `build` and model classes under
`khaos.<domain>.models`.

All architectures export to ONNX with a dynamic batch dimension, and a dynamic
length where the domain needs one (nodes, atoms, timesteps, tokens). The tests
check that ONNX Runtime reproduces PyTorch's output.

| Domain | Architecture family | Artifacts |
| - | - | - |
| Finance | Transformer NER | `sec_10k_core`, `sec_8k_events`, `sec_form4_insider`, `sec_s1_ipo` |
| Physics | Fourier Neural Operator | `pde_darcy_flow_2d`, `pde_navier_stokes_steady_2d`, `pde_heat_diffusion_2d`, `pde_wave_evolution_2d` |
| Robotics | Trajectory transformer | `robo_kinematics_sm`, `robo_skill_segmentation`, `robo_failure_detection` |
| Telemetry | Patch transformer, LSTM | `tele_sensor_vibration`, `tele_bio_ecg`, `tele_regime_shift` |
| Graph | GCN, graph transformer | `graph_node_embedding`, `graph_subgraph_embedding`, `graph_fraud_rings`, `graph_link_prediction` |
| Chemistry | SMILES transformer plus molecular GNN | `chem_mol_embedding`, `chem_logp`, `chem_solubility`, `chem_toxicity` |
| Geometry | Dynamic graph CNN (DGCNN), attention point encoder | `geo_part_classifier`, `geo_mesh_embedding`, `geo_pointcloud_embedding` |
| Tabular | Character CNN, DistilBERT cross-encoder, masked-cell transformer | `tab_column_types`, `tab_key_matching`, `tab_entity_dedupe`, `tab_anomaly_scoring` |

## Finance

Named-entity recognition on the raw text of SEC filings. `FilingNER` is a Hugging
Face encoder with a BIO token-classification head. It returns per-token `logits`
for entity extraction and a mean-pooled `vector`, the filing or chunk embedding.

| Artifact | Entity types |
| - | - |
| `sec_10k_core` | `REVENUE`, `INCOME_EXPENSE`, `DEBT`, `INTEREST_RATE`, `MATURITY_DATE`, `SHARE_COUNT`, `PRICE_PER_SHARE`, `ACQUISITION`, `STOCK_COMPENSATION`, `LEGAL_CONTINGENCY`, `TIME_PERIOD`, `ASSET_OR_EQUITY`, `PERCENTAGE_OTHER`, `COUNT_OR_AREA`, `OTHER_AMOUNT`, `DEBT_INSTRUMENT_NAME`, `GOING_CONCERN` |
| `sec_8k_events` | `EVENT_TYPE`, `PERSON`, `ROLE`, `COMPANY`, `DEAL_VALUE`, `DATE` |
| `sec_form4_insider` | `PERSON`, `ROLE`, `SECURITY_TYPE`, `SHARE_COUNT`, `PRICE`, `TRANSACTION_CODE`, `DATE` |
| `sec_s1_ipo` | `USE_OF_PROCEEDS`, `AMOUNT`, `LOCKUP_PERIOD`, `SHARE_COUNT`, `PRICE`, `DATE` |

```python theme={null}
from khaos.finance.models import build, bio_labels, ENTITY_TYPES

model = build("sec_10k_core")                              # distilbert-base-uncased
model = build("sec_10k_core", model_name="roberta-base")   # any Hugging Face encoder
model = build("sec_10k_core", pretrained=False)            # random weights, config only

labels = bio_labels(ENTITY_TYPES["sec_10k_core"])  # ["O", "B-REVENUE", "I-REVENUE", ...]
logits, vector = model(input_ids, attention_mask)
```

The default encoder is a compact DistilBERT so the model stays local-first friendly;
swap in a larger or finance-tuned encoder with `model_name`. Filings are far longer
than an encoder's context, so two helpers cover the text side:

```python theme={null}
from khaos.finance.models import chunk_ids, decode_entities

windows = chunk_ids(token_ids, max_len=510, stride=64)   # overlapping windows
entities = decode_entities(text, offsets, predicted_tags)
# [{'type': 'REVENUE', 'start': 24, 'end': 38, 'text': '$12.4 billion'}, ...]
```

## Physics

The four physics artifacts use Fourier Neural Operators (FNOs) on a fixed 64 x 64
grid. Artifact names end in `_2d` for the grid dimensionality; 3D variants (`_3d`)
are planned but not built yet.

Every model solves a **scenario**: the input holds the fields and the boundary
conditions, so the same network answers for different boundaries. A boundary
condition is two channels, a mask (where it applies) and its values. Scalar PDE
parameters such as viscosity go in a separate `params` input.

| Artifact | Class | Input channels `x` | `params` | Output |
| - | - | - | - | - |
| `pde_darcy_flow_2d` | `FNO2d` | permeability, source, dirichlet mask, dirichlet value | none | pressure `(1)` |
| `pde_navier_stokes_steady_2d` | `FNO2d` | solid mask, wall u velocity, wall v velocity | viscosity | velocity `(2)` |
| `pde_heat_diffusion_2d` | `TimeConditionedFNO2d` | initial temperature, dirichlet mask, dirichlet value, source | diffusivity | temperature `(1)` at time `t` |
| `pde_wave_evolution_2d` | `TimeConditionedFNO2d` | initial displacement, initial velocity, fixed-edge mask, free-edge mask | wave speed | displacement and velocity `(2)` at time `t` |

`FNO2d` handles steady problems, where the output depends only on the scenario.
`TimeConditionedFNO2d` also takes a time `t`, so you can query the state at any time
directly instead of stepping a solver. The datasets describe each channel in detail.

```python theme={null}
model = km.build("pde_heat_diffusion_2d")
pred = model(x, t, params)     # x: (batch, 4, 64, 64), t: (batch,), params: (batch, 1)
```

| Model | ONNX inputs | Output |
| - | - | - |
| `FNO2d` | `x`: `(batch, C, H, W)`, `params`: `(batch, P)` if the problem has parameters | `y`: `(batch, out_channels, H, W)` |
| `TimeConditionedFNO2d` | `x`, `t`: `(batch,)`, `params` if any | `y`: `(batch, out_channels, H, W)` |

The trained artifacts are wrapped in `khaos.physics.models.Normalized`, which
standardizes inputs and rescales outputs inside the exported model. Serving takes raw
physical values, so you do not normalize anything yourself.

> [!NOTE]
>
> The grid resolution is fixed when you build the model, and the exported ONNX
> model only accepts that grid size. Train and serve at the same resolution, or
> export a separate artifact per resolution.

## Robotics

Transformer encoders over `(T, state_dim)` trajectories. Inputs are `traj`
`(batch, T, state_dim)` and `mask` `(batch, T)` with 1 for real timesteps and 0
for padding, so variable-length trajectories batch together.

| Artifact | Class | Outputs |
| - | - | - |
| `robo_kinematics_sm` | `TrajectoryTransformer` | `vector`: embedding for similarity search |
| `robo_skill_segmentation` | `SkillSegmenter` | `boundary_logits` per step, `skill_logits` per step (6 skills) |
| `robo_failure_detection` | `FailureDetector` | `failure_logits` per step |

`FailureDetector` uses causal attention, so the logit at each timestep depends only
on past states. That makes it safe for a real-time loop: read the logit at the last
timestep.

```python theme={null}
from khaos.robotics.models import build

model = build("robo_kinematics_sm", state_dim=7, dim=256)
vector = model(traj, mask)

# trained artifacts wrap the model so it takes raw joint positions
from khaos.robotics.models import NormalizedTraj
model = NormalizedTraj(model, mean, std)
```

## Telemetry

Models for fixed-length sensor windows `(batch, channels, length)`, split into
patches. Each window is normalized inside the model, so raw sensor units work.

| Artifact | Class | Outputs |
| - | - | - |
| `tele_sensor_vibration` | `SensorTransformer` | `vector`, `anomaly_score` |
| `tele_bio_ecg` | `SensorLSTMAutoencoder` | `vector`, `anomaly_score` |
| `tele_regime_shift` | `RegimeShiftTransformer` | `change_logits` per patch |

The two autoencoders give a zero-shot anomaly score: the reconstruction error on the
normalized window. Pre-train on healthy data with `model.reconstruct(x)`, which
returns the reconstruction and the normalized input for your loss, optionally masking
patches first.

```python theme={null}
from khaos.telemetry.models import build

model = build("tele_sensor_vibration", length=3200, patch_len=64)
recon, target = model.reconstruct(x)
loss = ((recon - target) ** 2).mean()
```

`length` must be a multiple of `patch_len`, and the exported model accepts that
window length. Slice streams into windows before calling it. The defaults are 3,200
samples for vibration, 2,048 for ECG, and 8 channels by 512 samples for regime
shifts (streams with fewer channels are zero-padded). The vibration autoencoder
squeezes each patch through a 16-number bottleneck so it cannot just copy its input.

## Graph

Models for one graph per call: node features `x` `(N, F)` and a dense adjacency
`adj` `(N, N)`. `N` is dynamic. Dense adjacency keeps the models free of sparse
operations so they export to ONNX; for very large graphs, run them on sampled
subgraphs.

| Artifact | Class | Outputs |
| - | - | - |
| `graph_node_embedding` | `GCNAutoencoder` | `embeddings` `(N, dim)` |
| `graph_subgraph_embedding` | `GraphTransformerEncoder` | `vector` `(dim,)`, `embeddings` |
| `graph_fraud_rings` | `NodeAnomalyGCN` | `scores` `(N,)` in `[0, 1]` |
| `graph_link_prediction` | `LinkPredictor` | `probs` for candidate `pairs` `(P, 2)` |

`GCNAutoencoder` has a `reconstruct(x, adj)` method for masked-feature pre-training.
Fraud rings are the connected groups of high-scoring nodes, which a pipeline extracts
after the model runs.

```python theme={null}
from khaos.graph.models import build

model = build("graph_fraud_rings", in_dim=32)
scores = model(x, adj)
```

## Chemistry

A SMILES transformer (1D) and a GIN-style molecular graph network (2D), fused into a
single molecule vector. Featurization (RDKit atom features and adjacency) belongs to
your data pipeline; the models take tensors.

| Input | Shape |
| - | - |
| `tokens` | `(batch, L)` SMILES ids, 0 for padding |
| `atoms` | `(batch, N, atom_dim)` atom features, zero-padded |
| `adj` | `(batch, N, N)` bond adjacency |
| `atom_mask` | `(batch, N)` 1 for real atoms |

| Artifact | Class | Output |
| - | - | - |
| `chem_mol_embedding` | `HybridMoleculeEncoder` | `vector` `(batch, dim)` |
| `chem_logp` | `MoleculePropertyModel` | `value` (regression) |
| `chem_solubility` | `MoleculePropertyModel` | `value` (regression) |
| `chem_toxicity` | `MoleculePropertyModel` | `value` `(batch, 13)`: sigmoid probability per task (12 Tox21 assays and ClinTox) |

A pure-Python tokenizer for the SMILES ids lives in `khaos.chem.tokenizer`, with no
RDKit or PyTorch needed:

```python theme={null}
from khaos.chem.tokenizer import SmilesTokenizer
from khaos.chem.models import build

tokenizer = SmilesTokenizer.from_corpus(training_smiles)
ids = tokenizer.encode("CC(=O)OC1=CC=CC=C1C(=O)O", max_len=128)

model = build("chem_logp", vocab_size=len(tokenizer), atom_dim=32)
```

## Geometry

Point-set networks. Every model takes a fixed-size point set `points`
`(batch, channels, 512)`: sample a mesh or scan to 512 points, center it and scale it
to the unit sphere first. The `k`-nearest-neighbor graph is rebuilt inside the model,
and everything exports to ONNX with a dynamic batch.

| Artifact | Class | Input channels | Output |
| - | - | - | - |
| `geo_part_classifier` | `DGCNNClassifier` | `xyz` (3) | `logits` `(batch, 40)` |
| `geo_mesh_embedding` | `MeshEncoder` | `xyz` and surface normals (6) | `vector` `(batch, 256)`, unit length |
| `geo_pointcloud_embedding` | `PointCloudEncoder` | `xyz` (3) | `vector` `(batch, 256)`, unit length |

The embeddings are unit vectors, so cosine similarity is a dot product. The mesh encoder
sees normals, which separate shapes that share an outline; the scan encoder adds
attention pooling to cope with noise, occlusion and background points.

```python theme={null}
from khaos.geometry.models import build

model = build("geo_mesh_embedding")        # 512 points, k=16
vector = model(points)                     # points: (batch, 6, 512)
```

> [!NOTE]
>
> The number of points is fixed when you build the model, and the exported ONNX model
> only accepts that many. The first release is trained on 512 points.

## Tabular

Four different models for four different table problems.

| Artifact | Class | Inputs | Output |
| - | - | - | - |
| `tab_column_types` | `ColumnTypeCNN` | `chars` `(batch, cells, 40)` byte ids of sampled cells | `logits` over 91 types, `vector` |
| `tab_key_matching` | `ColumnPairMatcher` | `chars_a`, `chars_b`, 11 overlap `features` | `logit` that A is a foreign key of B |
| `tab_entity_dedupe` | `RecordMatcher` | tokenized record pair `input_ids`, `attention_mask` | `logit` that the two records match |
| `tab_anomaly_scoring` | `TabularAnomalyTransformer` | `values`, `visible`, `present`, `col_ids` over up to 64 columns | `recon`, a prediction for every cell |

`khaos.tabular.text` has the pure-Python helpers that build these inputs:
`encode_column` turns a sample of cells into byte ids, `pair_features` computes the
overlap features, `serialize_record` writes a record as `column: value | ...`, and
`robust_scale` scales a numeric column.

The anomaly model is a masked-cell transformer. Each column of a row is a token, and
the model learns to predict hidden cells from the visible ones. To score a table, hide a
random 25% of the cells, run the model a few times with different masks, and use the
average error on hidden cells as the row's anomaly score. Column ids are arbitrary slots
that training shuffles, so the model reasons from the other values rather than from fixed
column meanings, which is what lets it score tables it has never seen.

```python theme={null}
from khaos.tabular.models import build

model = build("tab_anomaly_scoring")       # up to 64 columns
recon = model(values, visible, present, col_ids)
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.