khaos-ml 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- khaos_ml-1.0.0/.gitignore +16 -0
- khaos_ml-1.0.0/PKG-INFO +195 -0
- khaos_ml-1.0.0/README.md +126 -0
- khaos_ml-1.0.0/khaos/__init__.py +4 -0
- khaos_ml-1.0.0/khaos/chem/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/chem/adapter.py +1 -0
- khaos_ml-1.0.0/khaos/chem/containers.py +17 -0
- khaos_ml-1.0.0/khaos/chem/features.py +41 -0
- khaos_ml-1.0.0/khaos/chem/models/__init__.py +24 -0
- khaos_ml-1.0.0/khaos/chem/models/configs.py +17 -0
- khaos_ml-1.0.0/khaos/chem/models/molecule.py +132 -0
- khaos_ml-1.0.0/khaos/chem/pipelines.py +61 -0
- khaos_ml-1.0.0/khaos/chem/tokenizer.py +32 -0
- khaos_ml-1.0.0/khaos/cli/__init__.py +45 -0
- khaos_ml-1.0.0/khaos/cli/__main__.py +5 -0
- khaos_ml-1.0.0/khaos/export.py +56 -0
- khaos_ml-1.0.0/khaos/finance/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/finance/adapter.py +1 -0
- khaos_ml-1.0.0/khaos/finance/containers.py +12 -0
- khaos_ml-1.0.0/khaos/finance/models/__init__.py +26 -0
- khaos_ml-1.0.0/khaos/finance/models/configs.py +29 -0
- khaos_ml-1.0.0/khaos/finance/models/labels.py +19 -0
- khaos_ml-1.0.0/khaos/finance/models/ner.py +56 -0
- khaos_ml-1.0.0/khaos/finance/models/text.py +47 -0
- khaos_ml-1.0.0/khaos/finance/pipelines.py +65 -0
- khaos_ml-1.0.0/khaos/geometry/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/geometry/adapter.py +1 -0
- khaos_ml-1.0.0/khaos/geometry/classes.py +6 -0
- khaos_ml-1.0.0/khaos/geometry/containers.py +18 -0
- khaos_ml-1.0.0/khaos/geometry/models/__init__.py +13 -0
- khaos_ml-1.0.0/khaos/geometry/models/configs.py +15 -0
- khaos_ml-1.0.0/khaos/geometry/models/layers.py +39 -0
- khaos_ml-1.0.0/khaos/geometry/models/point.py +102 -0
- khaos_ml-1.0.0/khaos/geometry/pipelines.py +75 -0
- khaos_ml-1.0.0/khaos/graph/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/graph/adapter.py +1 -0
- khaos_ml-1.0.0/khaos/graph/containers.py +25 -0
- khaos_ml-1.0.0/khaos/graph/models/__init__.py +28 -0
- khaos_ml-1.0.0/khaos/graph/models/configs.py +19 -0
- khaos_ml-1.0.0/khaos/graph/models/gnn.py +148 -0
- khaos_ml-1.0.0/khaos/graph/pipelines.py +122 -0
- khaos_ml-1.0.0/khaos/layers.py +58 -0
- khaos_ml-1.0.0/khaos/manifest.py +47 -0
- khaos_ml-1.0.0/khaos/modeling.py +39 -0
- khaos_ml-1.0.0/khaos/physics/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/physics/adapter.py +1 -0
- khaos_ml-1.0.0/khaos/physics/containers.py +10 -0
- khaos_ml-1.0.0/khaos/physics/models/__init__.py +28 -0
- khaos_ml-1.0.0/khaos/physics/models/configs.py +37 -0
- khaos_ml-1.0.0/khaos/physics/models/export.py +3 -0
- khaos_ml-1.0.0/khaos/physics/models/fno.py +116 -0
- khaos_ml-1.0.0/khaos/physics/models/normalize.py +51 -0
- khaos_ml-1.0.0/khaos/physics/models/spectral.py +93 -0
- khaos_ml-1.0.0/khaos/physics/pipelines.py +36 -0
- khaos_ml-1.0.0/khaos/pipeline.py +85 -0
- khaos_ml-1.0.0/khaos/registry.py +114 -0
- khaos_ml-1.0.0/khaos/robotics/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/robotics/adapter.py +1 -0
- khaos_ml-1.0.0/khaos/robotics/containers.py +26 -0
- khaos_ml-1.0.0/khaos/robotics/models/__init__.py +20 -0
- khaos_ml-1.0.0/khaos/robotics/models/configs.py +12 -0
- khaos_ml-1.0.0/khaos/robotics/models/normalize.py +23 -0
- khaos_ml-1.0.0/khaos/robotics/models/sequence.py +102 -0
- khaos_ml-1.0.0/khaos/robotics/pipelines.py +47 -0
- khaos_ml-1.0.0/khaos/robotics/skills.py +3 -0
- khaos_ml-1.0.0/khaos/serve/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/serve/app.py +96 -0
- khaos_ml-1.0.0/khaos/serve/encode.py +19 -0
- khaos_ml-1.0.0/khaos/tabular/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/tabular/adapter.py +1 -0
- khaos_ml-1.0.0/khaos/tabular/containers.py +32 -0
- khaos_ml-1.0.0/khaos/tabular/models/__init__.py +14 -0
- khaos_ml-1.0.0/khaos/tabular/models/anomaly.py +49 -0
- khaos_ml-1.0.0/khaos/tabular/models/column.py +80 -0
- khaos_ml-1.0.0/khaos/tabular/models/configs.py +30 -0
- khaos_ml-1.0.0/khaos/tabular/models/record.py +42 -0
- khaos_ml-1.0.0/khaos/tabular/pipelines.py +164 -0
- khaos_ml-1.0.0/khaos/tabular/text.py +59 -0
- khaos_ml-1.0.0/khaos/telemetry/__init__.py +3 -0
- khaos_ml-1.0.0/khaos/telemetry/adapter.py +1 -0
- khaos_ml-1.0.0/khaos/telemetry/containers.py +18 -0
- khaos_ml-1.0.0/khaos/telemetry/models/__init__.py +22 -0
- khaos_ml-1.0.0/khaos/telemetry/models/configs.py +25 -0
- khaos_ml-1.0.0/khaos/telemetry/models/sensor.py +205 -0
- khaos_ml-1.0.0/khaos/telemetry/pipelines.py +47 -0
- khaos_ml-1.0.0/pyproject.toml +49 -0
- khaos_ml-1.0.0/tests/conftest.py +25 -0
- khaos_ml-1.0.0/tests/test_finance_models.py +56 -0
- khaos_ml-1.0.0/tests/test_geometry_tabular_models.py +96 -0
- khaos_ml-1.0.0/tests/test_load.py +24 -0
- khaos_ml-1.0.0/tests/test_models.py +93 -0
- khaos_ml-1.0.0/tests/test_onnx.py +41 -0
- khaos_ml-1.0.0/tests/test_physics_models.py +56 -0
- khaos_ml-1.0.0/tests/test_pipelines.py +144 -0
- khaos_ml-1.0.0/tests/test_serve.py +48 -0
khaos_ml-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: khaos-ml
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Local-first pre-trained models for domain-specific tasks: finance, physics, robotics, 3D, tabular, telemetry, graph and chemistry
|
|
5
|
+
Author: fletxcher
|
|
6
|
+
Keywords: cheminformatics,entity-resolution,machine-learning,onnx,pde,pretrained-models,robotics,sec-filings
|
|
7
|
+
Classifier: Development Status :: 4 - Beta
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Requires-Dist: huggingface-hub
|
|
18
|
+
Requires-Dist: numpy
|
|
19
|
+
Requires-Dist: onnxruntime
|
|
20
|
+
Provides-Extra: 3d
|
|
21
|
+
Requires-Dist: trimesh; extra == '3d'
|
|
22
|
+
Provides-Extra: all
|
|
23
|
+
Requires-Dist: fastapi; extra == 'all'
|
|
24
|
+
Requires-Dist: pandas; extra == 'all'
|
|
25
|
+
Requires-Dist: python-multipart; extra == 'all'
|
|
26
|
+
Requires-Dist: rdkit; extra == 'all'
|
|
27
|
+
Requires-Dist: transformers; extra == 'all'
|
|
28
|
+
Requires-Dist: trimesh; extra == 'all'
|
|
29
|
+
Requires-Dist: uvicorn; extra == 'all'
|
|
30
|
+
Provides-Extra: chem
|
|
31
|
+
Requires-Dist: rdkit; extra == 'chem'
|
|
32
|
+
Provides-Extra: data
|
|
33
|
+
Requires-Dist: datasets; extra == 'data'
|
|
34
|
+
Requires-Dist: h5py; extra == 'data'
|
|
35
|
+
Requires-Dist: networkx; extra == 'data'
|
|
36
|
+
Requires-Dist: pandas; extra == 'data'
|
|
37
|
+
Requires-Dist: pyarrow; extra == 'data'
|
|
38
|
+
Requires-Dist: python-dotenv; extra == 'data'
|
|
39
|
+
Requires-Dist: rdkit; extra == 'data'
|
|
40
|
+
Requires-Dist: scikit-learn; extra == 'data'
|
|
41
|
+
Requires-Dist: scipy; extra == 'data'
|
|
42
|
+
Requires-Dist: trimesh; extra == 'data'
|
|
43
|
+
Requires-Dist: wfdb; extra == 'data'
|
|
44
|
+
Provides-Extra: dev
|
|
45
|
+
Requires-Dist: httpx; extra == 'dev'
|
|
46
|
+
Requires-Dist: onnx; extra == 'dev'
|
|
47
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
48
|
+
Provides-Extra: finance
|
|
49
|
+
Requires-Dist: beautifulsoup4; extra == 'finance'
|
|
50
|
+
Requires-Dist: lxml; extra == 'finance'
|
|
51
|
+
Requires-Dist: transformers; extra == 'finance'
|
|
52
|
+
Provides-Extra: graph
|
|
53
|
+
Requires-Dist: networkx; extra == 'graph'
|
|
54
|
+
Provides-Extra: serve
|
|
55
|
+
Requires-Dist: fastapi; extra == 'serve'
|
|
56
|
+
Requires-Dist: python-multipart; extra == 'serve'
|
|
57
|
+
Requires-Dist: uvicorn; extra == 'serve'
|
|
58
|
+
Provides-Extra: tabular
|
|
59
|
+
Requires-Dist: pandas; extra == 'tabular'
|
|
60
|
+
Requires-Dist: transformers; extra == 'tabular'
|
|
61
|
+
Provides-Extra: telemetry
|
|
62
|
+
Requires-Dist: scipy; extra == 'telemetry'
|
|
63
|
+
Provides-Extra: train
|
|
64
|
+
Requires-Dist: onnx; extra == 'train'
|
|
65
|
+
Requires-Dist: scikit-learn; extra == 'train'
|
|
66
|
+
Requires-Dist: torch; extra == 'train'
|
|
67
|
+
Requires-Dist: transformers; extra == 'train'
|
|
68
|
+
Description-Content-Type: text/markdown
|
|
69
|
+
|
|
70
|
+
# khaos: Pre-trained models for domain-specific tasks
|
|
71
|
+
|
|
72
|
+
khaos is a lightweight, modular, **local-first** machine learning framework for
|
|
73
|
+
Python. It ships compact pre-trained models for specialized engineering,
|
|
74
|
+
scientific and financial data, behind one small API, so you can run them on
|
|
75
|
+
standard CPU/edge hardware without sending data to an external service.
|
|
76
|
+
|
|
77
|
+
> **Version:** Khaos is on **v1**. The first release of every artifact is named
|
|
78
|
+
> `v1`; we do not use `v0.x` versions. The runtime, architectures and serving are in
|
|
79
|
+
> place, and artifacts are being trained and published domain by domain.
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
import khaos
|
|
83
|
+
|
|
84
|
+
nlp = khaos.load("sec_10k_core")
|
|
85
|
+
doc = nlp("path/to/10k_filing.html")
|
|
86
|
+
print(doc.ents) # extracted metrics, debt tranches, maturity dates
|
|
87
|
+
# [Entity(label="Revenue", value="$12.4B"), ...]
|
|
88
|
+
print(doc.vector) # dense filing embedding
|
|
89
|
+
# [ 0.12 -0.03 0.88 ... ]
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Features
|
|
93
|
+
|
|
94
|
+
- One `khaos.load(...)` interface for every domain
|
|
95
|
+
- Pre-trained artifacts per vertical, fetched and cached from the Hugging Face Hub
|
|
96
|
+
- ONNX inference behind a lightweight core runtime; export from PyTorch, TensorFlow or any other library
|
|
97
|
+
- Heavy domain dependencies isolated as optional extras
|
|
98
|
+
- Pipelines resolved through a registry, so new artifacts plug in without touching core
|
|
99
|
+
- Built-in HTTP server (`khaos serve`) and Dockerfile for deployment
|
|
100
|
+
- `khaos` command-line interface for inspecting, downloading, serving and evaluating artifacts
|
|
101
|
+
- Domain-specific result containers: each vertical defines its own, with no shared base class
|
|
102
|
+
|
|
103
|
+
## Verticals and artifacts
|
|
104
|
+
|
|
105
|
+
| Extra | Domain | Example artifacts |
|
|
106
|
+
| --- | --- | --- |
|
|
107
|
+
| `khaos-ml[finance]` | SEC filings and XBRL extraction | `sec_10k_core`, `sec_8k_events`, `sec_form4_insider`, `sec_s1_ipo` |
|
|
108
|
+
| `khaos-ml[3d]` | CAD, meshes and point clouds | `geo_part_classifier`, `geo_mesh_embedding`, `geo_pointcloud_embedding` |
|
|
109
|
+
| `khaos-ml[tabular]` | Schema detection and entity resolution | `tab_column_types`, `tab_key_matching`, `tab_entity_dedupe`, `tab_anomaly_scoring` |
|
|
110
|
+
| `khaos-ml[telemetry]` | Industrial and IoT sensor time-series | `tele_sensor_vibration`, `tele_bio_ecg`, `tele_regime_shift` |
|
|
111
|
+
| `khaos-ml[graph]` | Graph and network topology encoders | `graph_node_embedding`, `graph_subgraph_embedding`, `graph_fraud_rings`, `graph_link_prediction` |
|
|
112
|
+
| `khaos-ml[chem]` | Molecular and material properties | `chem_mol_embedding`, `chem_logp`, `chem_solubility`, `chem_toxicity` |
|
|
113
|
+
| `khaos-ml` (core) | PDE simulation surrogates | `pde_darcy_flow_2d`, `pde_navier_stokes_steady_2d`, `pde_heat_diffusion_2d`, `pde_wave_evolution_2d` |
|
|
114
|
+
| `khaos-ml` (core) | Robot trajectory and kinematics encoders | `robo_kinematics_sm`, `robo_skill_segmentation`, `robo_failure_detection` |
|
|
115
|
+
|
|
116
|
+
See [`idea.txt`](idea.txt) for the full vision and roadmap.
|
|
117
|
+
|
|
118
|
+
## Installation
|
|
119
|
+
|
|
120
|
+
Requires Python 3.10+. The package is named `khaos-ml`; the import is `khaos`.
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
pip install khaos-ml # or: poetry add khaos-ml / uv add khaos-ml
|
|
124
|
+
pip install "khaos-ml[all]" # everything needed to run every artifact
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Serve it
|
|
128
|
+
|
|
129
|
+
Train elsewhere, export to ONNX, and serve:
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
pip install "khaos-ml[serve]"
|
|
133
|
+
khaos serve ./my-artifact --port 8000
|
|
134
|
+
curl -X POST localhost:8000/v1/artifacts/pde_darcy_flow_2d/predict \
|
|
135
|
+
-H "Content-Type: application/json" -d '{"input": [[0.0, 0.1], [0.2, 0.3]]}'
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
See the docs for the artifact format, authentication and Docker.
|
|
139
|
+
|
|
140
|
+
## Command line
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
khaos info # list known artifacts
|
|
144
|
+
khaos download <artifact> # fetch an artifact from the Hugging Face Hub
|
|
145
|
+
khaos serve [artifact ...] # serve artifacts over HTTP
|
|
146
|
+
khaos evaluate <artifact> # evaluate an artifact (not implemented yet)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Repository layout
|
|
150
|
+
|
|
151
|
+
```text
|
|
152
|
+
khaos/
|
|
153
|
+
├── pyproject.toml
|
|
154
|
+
├── khaos/ # importable package
|
|
155
|
+
│ ├── registry.py # artifact registry and load()
|
|
156
|
+
│ ├── manifest.py # artifact manifest (training -> runtime contract)
|
|
157
|
+
│ ├── modeling.py # khaos.modeling.build(artifact)
|
|
158
|
+
│ ├── export.py # export_artifact(): model -> manifest + ONNX
|
|
159
|
+
│ ├── layers.py # ONNX-friendly transformer blocks
|
|
160
|
+
│ ├── pipeline.py # BasePipeline, OnnxPipeline, ModalityProcessor
|
|
161
|
+
│ ├── serve/ # HTTP server
|
|
162
|
+
│ ├── cli/ # `khaos` command
|
|
163
|
+
│ └── finance/ geometry/ tabular/ telemetry/ graph/ chem/ physics/ robotics/
|
|
164
|
+
│ # one subpackage per vertical (adapter, pipelines,
|
|
165
|
+
│ # and its own containers.py)
|
|
166
|
+
├── artifacts/ # artifact definitions, one dir per domain
|
|
167
|
+
├── docs/ # documentation site (Mintlify)
|
|
168
|
+
├── training/ # per-artifact training and evaluation configs
|
|
169
|
+
└── tests/
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Model weights are not stored in this repository; they are published to the
|
|
173
|
+
Hugging Face Hub and cached under `~/.cache/khaos`.
|
|
174
|
+
|
|
175
|
+
## Documentation
|
|
176
|
+
|
|
177
|
+
Docs live in `docs/` and are built with [Mintlify](https://www.mintlify.com/docs):
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
npm i -g mint
|
|
181
|
+
cd docs && mint dev # http://localhost:3000
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## Run tests
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
pip install -e ".[dev]"
|
|
188
|
+
python -m pytest tests
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Roadmap
|
|
192
|
+
|
|
193
|
+
- [ ] **Phase 1:** core runtime (`khaos.load()`, Hub caching, ONNX inference, per-domain result containers)
|
|
194
|
+
- [ ] **Phase 2:** flagship artifact (`sec_10k_core` trained on SEC EDGAR iXBRL data)
|
|
195
|
+
- [ ] **Phase 3:** multi-modal expansion across the remaining verticals
|
khaos_ml-1.0.0/README.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# khaos: Pre-trained models for domain-specific tasks
|
|
2
|
+
|
|
3
|
+
khaos is a lightweight, modular, **local-first** machine learning framework for
|
|
4
|
+
Python. It ships compact pre-trained models for specialized engineering,
|
|
5
|
+
scientific and financial data, behind one small API, so you can run them on
|
|
6
|
+
standard CPU/edge hardware without sending data to an external service.
|
|
7
|
+
|
|
8
|
+
> **Version:** Khaos is on **v1**. The first release of every artifact is named
|
|
9
|
+
> `v1`; we do not use `v0.x` versions. The runtime, architectures and serving are in
|
|
10
|
+
> place, and artifacts are being trained and published domain by domain.
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
import khaos
|
|
14
|
+
|
|
15
|
+
nlp = khaos.load("sec_10k_core")
|
|
16
|
+
doc = nlp("path/to/10k_filing.html")
|
|
17
|
+
print(doc.ents) # extracted metrics, debt tranches, maturity dates
|
|
18
|
+
# [Entity(label="Revenue", value="$12.4B"), ...]
|
|
19
|
+
print(doc.vector) # dense filing embedding
|
|
20
|
+
# [ 0.12 -0.03 0.88 ... ]
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
- One `khaos.load(...)` interface for every domain
|
|
26
|
+
- Pre-trained artifacts per vertical, fetched and cached from the Hugging Face Hub
|
|
27
|
+
- ONNX inference behind a lightweight core runtime; export from PyTorch, TensorFlow or any other library
|
|
28
|
+
- Heavy domain dependencies isolated as optional extras
|
|
29
|
+
- Pipelines resolved through a registry, so new artifacts plug in without touching core
|
|
30
|
+
- Built-in HTTP server (`khaos serve`) and Dockerfile for deployment
|
|
31
|
+
- `khaos` command-line interface for inspecting, downloading, serving and evaluating artifacts
|
|
32
|
+
- Domain-specific result containers: each vertical defines its own, with no shared base class
|
|
33
|
+
|
|
34
|
+
## Verticals and artifacts
|
|
35
|
+
|
|
36
|
+
| Extra | Domain | Example artifacts |
|
|
37
|
+
| --- | --- | --- |
|
|
38
|
+
| `khaos-ml[finance]` | SEC filings and XBRL extraction | `sec_10k_core`, `sec_8k_events`, `sec_form4_insider`, `sec_s1_ipo` |
|
|
39
|
+
| `khaos-ml[3d]` | CAD, meshes and point clouds | `geo_part_classifier`, `geo_mesh_embedding`, `geo_pointcloud_embedding` |
|
|
40
|
+
| `khaos-ml[tabular]` | Schema detection and entity resolution | `tab_column_types`, `tab_key_matching`, `tab_entity_dedupe`, `tab_anomaly_scoring` |
|
|
41
|
+
| `khaos-ml[telemetry]` | Industrial and IoT sensor time-series | `tele_sensor_vibration`, `tele_bio_ecg`, `tele_regime_shift` |
|
|
42
|
+
| `khaos-ml[graph]` | Graph and network topology encoders | `graph_node_embedding`, `graph_subgraph_embedding`, `graph_fraud_rings`, `graph_link_prediction` |
|
|
43
|
+
| `khaos-ml[chem]` | Molecular and material properties | `chem_mol_embedding`, `chem_logp`, `chem_solubility`, `chem_toxicity` |
|
|
44
|
+
| `khaos-ml` (core) | PDE simulation surrogates | `pde_darcy_flow_2d`, `pde_navier_stokes_steady_2d`, `pde_heat_diffusion_2d`, `pde_wave_evolution_2d` |
|
|
45
|
+
| `khaos-ml` (core) | Robot trajectory and kinematics encoders | `robo_kinematics_sm`, `robo_skill_segmentation`, `robo_failure_detection` |
|
|
46
|
+
|
|
47
|
+
See [`idea.txt`](idea.txt) for the full vision and roadmap.
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
Requires Python 3.10+. The package is named `khaos-ml`; the import is `khaos`.
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install khaos-ml # or: poetry add khaos-ml / uv add khaos-ml
|
|
55
|
+
pip install "khaos-ml[all]" # everything needed to run every artifact
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Serve it
|
|
59
|
+
|
|
60
|
+
Train elsewhere, export to ONNX, and serve:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install "khaos-ml[serve]"
|
|
64
|
+
khaos serve ./my-artifact --port 8000
|
|
65
|
+
curl -X POST localhost:8000/v1/artifacts/pde_darcy_flow_2d/predict \
|
|
66
|
+
-H "Content-Type: application/json" -d '{"input": [[0.0, 0.1], [0.2, 0.3]]}'
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
See the docs for the artifact format, authentication and Docker.
|
|
70
|
+
|
|
71
|
+
## Command line
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
khaos info # list known artifacts
|
|
75
|
+
khaos download <artifact> # fetch an artifact from the Hugging Face Hub
|
|
76
|
+
khaos serve [artifact ...] # serve artifacts over HTTP
|
|
77
|
+
khaos evaluate <artifact> # evaluate an artifact (not implemented yet)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Repository layout
|
|
81
|
+
|
|
82
|
+
```text
|
|
83
|
+
khaos/
|
|
84
|
+
├── pyproject.toml
|
|
85
|
+
├── khaos/ # importable package
|
|
86
|
+
│ ├── registry.py # artifact registry and load()
|
|
87
|
+
│ ├── manifest.py # artifact manifest (training -> runtime contract)
|
|
88
|
+
│ ├── modeling.py # khaos.modeling.build(artifact)
|
|
89
|
+
│ ├── export.py # export_artifact(): model -> manifest + ONNX
|
|
90
|
+
│ ├── layers.py # ONNX-friendly transformer blocks
|
|
91
|
+
│ ├── pipeline.py # BasePipeline, OnnxPipeline, ModalityProcessor
|
|
92
|
+
│ ├── serve/ # HTTP server
|
|
93
|
+
│ ├── cli/ # `khaos` command
|
|
94
|
+
│ └── finance/ geometry/ tabular/ telemetry/ graph/ chem/ physics/ robotics/
|
|
95
|
+
│ # one subpackage per vertical (adapter, pipelines,
|
|
96
|
+
│ # and its own containers.py)
|
|
97
|
+
├── artifacts/ # artifact definitions, one dir per domain
|
|
98
|
+
├── docs/ # documentation site (Mintlify)
|
|
99
|
+
├── training/ # per-artifact training and evaluation configs
|
|
100
|
+
└── tests/
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Model weights are not stored in this repository; they are published to the
|
|
104
|
+
Hugging Face Hub and cached under `~/.cache/khaos`.
|
|
105
|
+
|
|
106
|
+
## Documentation
|
|
107
|
+
|
|
108
|
+
Docs live in `docs/` and are built with [Mintlify](https://www.mintlify.com/docs):
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
npm i -g mint
|
|
112
|
+
cd docs && mint dev # http://localhost:3000
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Run tests
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
pip install -e ".[dev]"
|
|
119
|
+
python -m pytest tests
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Roadmap
|
|
123
|
+
|
|
124
|
+
- [ ] **Phase 1:** core runtime (`khaos.load()`, Hub caching, ONNX inference, per-domain result containers)
|
|
125
|
+
- [ ] **Phase 2:** flagship artifact (`sec_10k_core` trained on SEC EDGAR iXBRL data)
|
|
126
|
+
- [ ] **Phase 3:** multi-modal expansion across the remaining verticals
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Preprocessing adapter for molecules (stub)."""
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class MoleculeEmbedding:
|
|
8
|
+
"""Dense molecular embedding."""
|
|
9
|
+
|
|
10
|
+
vector: np.ndarray
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class PropertyPrediction:
|
|
15
|
+
"""Predicted physicochemical properties (LogP, solubility, toxicity, ...)."""
|
|
16
|
+
|
|
17
|
+
properties: dict[str, float] = field(default_factory=dict)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Turn a SMILES string into the three inputs of the chemistry models: tokens, atom features and bonds.
|
|
2
|
+
|
|
3
|
+
Needs RDKit (``pip install "khaos[chem]"``).
|
|
4
|
+
"""
|
|
5
|
+
import numpy as np
|
|
6
|
+
from rdkit import Chem, RDLogger
|
|
7
|
+
|
|
8
|
+
from khaos.chem.tokenizer import SmilesTokenizer
|
|
9
|
+
|
|
10
|
+
RDLogger.DisableLog("rdApp.*")
|
|
11
|
+
|
|
12
|
+
MAX_LEN, ATOM_DIM = 128, 32
|
|
13
|
+
ELEMENTS = [6, 7, 8, 9, 15, 16, 17, 35, 53]
|
|
14
|
+
HYBRIDS = [Chem.HybridizationType.SP, Chem.HybridizationType.SP2, Chem.HybridizationType.SP3]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def one_hot(value, choices, other=True):
|
|
18
|
+
vec = [float(value == c) for c in choices]
|
|
19
|
+
return vec + ([float(value not in choices)] if other else [])
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def atom_features(atom) -> list[float]:
|
|
23
|
+
ring = atom.GetOwningMol().GetRingInfo()
|
|
24
|
+
idx = atom.GetIdx()
|
|
25
|
+
return (one_hot(atom.GetAtomicNum(), ELEMENTS) + one_hot(min(atom.GetDegree(), 5), range(6), False)
|
|
26
|
+
+ one_hot(atom.GetFormalCharge(), (-1, 0, 1), False) + one_hot(min(atom.GetTotalNumHs(), 3), range(4), False)
|
|
27
|
+
+ one_hot(atom.GetHybridization(), HYBRIDS) + [float(atom.GetIsAromatic()), float(atom.IsInRing()),
|
|
28
|
+
float(ring.IsAtomInRingOfSize(idx, 5)), float(ring.IsAtomInRingOfSize(idx, 6)), atom.GetMass() / 100.0])
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def featurize(smiles: str, tokenizer: SmilesTokenizer, max_len: int = MAX_LEN):
|
|
32
|
+
"""(token ids, atom features (n, 32), adjacency (n, n)) for one molecule; ``ValueError`` if RDKit cannot parse it."""
|
|
33
|
+
mol = Chem.MolFromSmiles(smiles)
|
|
34
|
+
if mol is None or mol.GetNumAtoms() == 0:
|
|
35
|
+
raise ValueError(f"cannot parse SMILES {smiles!r}")
|
|
36
|
+
atoms = np.asarray([atom_features(a) for a in mol.GetAtoms()], np.float32)
|
|
37
|
+
adj = np.zeros((len(atoms), len(atoms)), np.float32)
|
|
38
|
+
for b in mol.GetBonds():
|
|
39
|
+
i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
|
|
40
|
+
adj[i, j] = adj[j, i] = 1.0
|
|
41
|
+
return np.asarray(tokenizer.encode(smiles, max_len), np.int64), atoms, adj
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""SMILES-transformer and molecular-graph architectures for the chem artifacts (``pip install khaos[train]``)."""
|
|
2
|
+
try:
|
|
3
|
+
import torch # noqa: F401
|
|
4
|
+
except ImportError as exc: # pragma: no cover
|
|
5
|
+
raise ImportError("khaos.chem.models needs PyTorch: pip install 'khaos[train]'") from exc
|
|
6
|
+
|
|
7
|
+
from khaos.chem.models.configs import ARCHITECTURES, build
|
|
8
|
+
from khaos.chem.models.molecule import (
|
|
9
|
+
HybridMoleculeEncoder,
|
|
10
|
+
MolGraphEncoder,
|
|
11
|
+
MoleculePropertyModel,
|
|
12
|
+
SmilesTransformer,
|
|
13
|
+
)
|
|
14
|
+
from khaos.export import export_artifact
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"ARCHITECTURES",
|
|
18
|
+
"HybridMoleculeEncoder",
|
|
19
|
+
"MolGraphEncoder",
|
|
20
|
+
"MoleculePropertyModel",
|
|
21
|
+
"SmilesTransformer",
|
|
22
|
+
"build",
|
|
23
|
+
"export_artifact",
|
|
24
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from khaos.chem.models.molecule import HybridMoleculeEncoder, MoleculePropertyModel
|
|
2
|
+
from khaos.modeling import Spec, build_from
|
|
3
|
+
|
|
4
|
+
# ``vocab_size`` and ``atom_dim`` must match your tokenizer and atom featurization.
|
|
5
|
+
ARCHITECTURES: dict[str, Spec] = {
|
|
6
|
+
"chem_mol_embedding": Spec(HybridMoleculeEncoder, dict(vocab_size=128, atom_dim=32, dim=256)),
|
|
7
|
+
"chem_logp": Spec(MoleculePropertyModel, dict(vocab_size=128, atom_dim=32, dim=256, n_out=1)),
|
|
8
|
+
"chem_solubility": Spec(MoleculePropertyModel, dict(vocab_size=128, atom_dim=32, dim=256, n_out=1)),
|
|
9
|
+
"chem_toxicity": Spec(
|
|
10
|
+
MoleculePropertyModel,
|
|
11
|
+
dict(vocab_size=128, atom_dim=32, dim=256, n_out=13, activation="sigmoid"),
|
|
12
|
+
),
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build(artifact: str, **overrides):
|
|
17
|
+
return build_from(ARCHITECTURES, artifact, **overrides)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Molecule encoders: a SMILES transformer, a graph network, and a hybrid of both.
|
|
2
|
+
|
|
3
|
+
Featurization (RDKit atom features and adjacency) is your data pipeline's job; the
|
|
4
|
+
models take tensors:
|
|
5
|
+
|
|
6
|
+
tokens (B, L) SMILES ids, 0 = padding (see ``khaos.chem.tokenizer``)
|
|
7
|
+
atoms (B, N, F) atom features, zero-padded
|
|
8
|
+
adj (B, N, N) bond adjacency, zero-padded
|
|
9
|
+
atom_mask (B, N) 1 for real atoms
|
|
10
|
+
"""
|
|
11
|
+
import torch
|
|
12
|
+
from torch import nn
|
|
13
|
+
|
|
14
|
+
from khaos.layers import TransformerBlock, padding_bias
|
|
15
|
+
|
|
16
|
+
_AXES = {
|
|
17
|
+
"tokens": {0: "batch", 1: "length"},
|
|
18
|
+
"atoms": {0: "batch", 1: "atoms"},
|
|
19
|
+
"adj": {0: "batch", 1: "atoms", 2: "atoms"},
|
|
20
|
+
"atom_mask": {0: "batch", 1: "atoms"},
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _masked_mean(h: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
|
|
25
|
+
m = mask.unsqueeze(-1).to(h.dtype)
|
|
26
|
+
return (h * m).sum(dim=1) / m.sum(dim=1).clamp(min=1.0)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class SmilesTransformer(nn.Module):
|
|
30
|
+
"""Transformer encoder over SMILES tokens; returns ``(B, dim)``."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, vocab_size=128, dim=256, depth=6, heads=8, max_len=128, dropout=0.0):
|
|
33
|
+
super().__init__()
|
|
34
|
+
self.max_len = max_len
|
|
35
|
+
self.tok = nn.Embedding(vocab_size, dim, padding_idx=0)
|
|
36
|
+
self.pos = nn.Embedding(max_len, dim)
|
|
37
|
+
self.blocks = nn.ModuleList(TransformerBlock(dim, heads, 4, dropout) for _ in range(depth))
|
|
38
|
+
self.norm = nn.LayerNorm(dim)
|
|
39
|
+
|
|
40
|
+
def forward(self, tokens: torch.Tensor) -> torch.Tensor:
|
|
41
|
+
mask = (tokens != 0).to(torch.float32)
|
|
42
|
+
steps = torch.cumsum(torch.ones_like(tokens), dim=1) - 1
|
|
43
|
+
h = self.tok(tokens) + self.pos(steps)
|
|
44
|
+
bias = padding_bias(mask)
|
|
45
|
+
for block in self.blocks:
|
|
46
|
+
h = block(h, bias)
|
|
47
|
+
return _masked_mean(self.norm(h), mask)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _GINLayer(nn.Module):
|
|
51
|
+
def __init__(self, dim: int):
|
|
52
|
+
super().__init__()
|
|
53
|
+
self.eps = nn.Parameter(torch.zeros(1))
|
|
54
|
+
self.mlp = nn.Sequential(nn.Linear(dim, dim), nn.GELU(), nn.Linear(dim, dim))
|
|
55
|
+
self.norm = nn.LayerNorm(dim)
|
|
56
|
+
|
|
57
|
+
def forward(self, h, adj, mask):
|
|
58
|
+
h = h + self.mlp(self.norm((1 + self.eps) * h + adj @ h))
|
|
59
|
+
return h * mask.unsqueeze(-1)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class MolGraphEncoder(nn.Module):
|
|
63
|
+
"""GIN-style message passing over the molecular graph; returns ``(B, dim)``."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, atom_dim=32, dim=256, layers=4):
|
|
66
|
+
super().__init__()
|
|
67
|
+
self.embed = nn.Linear(atom_dim, dim)
|
|
68
|
+
self.layers = nn.ModuleList(_GINLayer(dim) for _ in range(layers))
|
|
69
|
+
|
|
70
|
+
def forward(self, atoms, adj, atom_mask):
|
|
71
|
+
h = self.embed(atoms) * atom_mask.unsqueeze(-1)
|
|
72
|
+
for layer in self.layers:
|
|
73
|
+
h = layer(h, adj, atom_mask)
|
|
74
|
+
return _masked_mean(h, atom_mask)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class HybridMoleculeEncoder(nn.Module):
|
|
78
|
+
"""1D (SMILES transformer) plus 2D (molecular graph) encoders fused into one vector."""
|
|
79
|
+
|
|
80
|
+
input_names = ("tokens", "atoms", "adj", "atom_mask")
|
|
81
|
+
output_names = ("vector",)
|
|
82
|
+
|
|
83
|
+
def __init__(self, vocab_size=128, atom_dim=32, dim=256, depth=6, heads=8, graph_layers=4, max_len=128, dropout=0.0):
|
|
84
|
+
super().__init__()
|
|
85
|
+
self.vocab_size, self.atom_dim, self.dim = vocab_size, atom_dim, dim
|
|
86
|
+
self.smiles = SmilesTransformer(vocab_size, dim, depth, heads, max_len, dropout)
|
|
87
|
+
self.graph = MolGraphEncoder(atom_dim, dim, graph_layers)
|
|
88
|
+
self.fuse = nn.Sequential(nn.Linear(2 * dim, dim), nn.GELU(), nn.Linear(dim, dim))
|
|
89
|
+
self.dynamic_axes = {**_AXES, "vector": {0: "batch"}}
|
|
90
|
+
|
|
91
|
+
def example_inputs(self, batch: int = 1):
|
|
92
|
+
return (
|
|
93
|
+
torch.ones(batch, 12, dtype=torch.long),
|
|
94
|
+
torch.zeros(batch, 10, self.atom_dim),
|
|
95
|
+
torch.zeros(batch, 10, 10),
|
|
96
|
+
torch.ones(batch, 10),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
def manifest_meta(self) -> dict:
|
|
100
|
+
return {"vocab_size": self.vocab_size, "atom_dim": self.atom_dim, "dim": self.dim}
|
|
101
|
+
|
|
102
|
+
def forward(self, tokens, atoms, adj, atom_mask):
|
|
103
|
+
z = torch.cat([self.smiles(tokens), self.graph(atoms, adj, atom_mask)], dim=-1)
|
|
104
|
+
return self.fuse(z)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class MoleculePropertyModel(HybridMoleculeEncoder):
|
|
108
|
+
"""Hybrid encoder plus a property head: ``value`` ``(B, n_out)``.
|
|
109
|
+
|
|
110
|
+
Set ``activation="sigmoid"`` for probabilities (e.g. toxicity); leave it as
|
|
111
|
+
``"none"`` for regression targets (LogP, solubility).
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
output_names = ("value",)
|
|
115
|
+
|
|
116
|
+
def __init__(self, n_out: int = 1, activation: str = "none", **kwargs):
|
|
117
|
+
super().__init__(**kwargs)
|
|
118
|
+
if activation not in ("none", "sigmoid"):
|
|
119
|
+
raise ValueError("activation must be 'none' or 'sigmoid'")
|
|
120
|
+
self.activation = activation
|
|
121
|
+
self.head = nn.Sequential(nn.Linear(self.dim, self.dim), nn.GELU(), nn.Linear(self.dim, n_out))
|
|
122
|
+
self.dynamic_axes = {**_AXES, "value": {0: "batch"}}
|
|
123
|
+
|
|
124
|
+
def manifest_meta(self) -> dict:
|
|
125
|
+
return {**super().manifest_meta(), "activation": self.activation}
|
|
126
|
+
|
|
127
|
+
def embed(self, tokens, atoms, adj, atom_mask):
|
|
128
|
+
return super().forward(tokens, atoms, adj, atom_mask)
|
|
129
|
+
|
|
130
|
+
def forward(self, tokens, atoms, adj, atom_mask):
|
|
131
|
+
out = self.head(self.embed(tokens, atoms, adj, atom_mask))
|
|
132
|
+
return torch.sigmoid(out) if self.activation == "sigmoid" else out
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Pipelines for the chemistry models. They need RDKit: ``pip install "khaos[chem]"``."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
from khaos.chem.containers import MoleculeEmbedding, PropertyPrediction
|
|
5
|
+
from khaos.chem.tokenizer import SmilesTokenizer
|
|
6
|
+
from khaos.pipeline import OnnxPipeline
|
|
7
|
+
from khaos.registry import register
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class MoleculePipeline(OnnxPipeline):
|
|
11
|
+
"""``raw`` is a SMILES string, or a list of them for a batch (the result is then a list). A string RDKit
|
|
12
|
+
cannot parse raises ``ValueError``."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, manifest, path):
|
|
15
|
+
super().__init__(manifest, path)
|
|
16
|
+
self._tokenizer = SmilesTokenizer(manifest.meta["tokenizer_vocab"])
|
|
17
|
+
|
|
18
|
+
def preprocess(self, raw):
|
|
19
|
+
from khaos.chem.features import featurize
|
|
20
|
+
|
|
21
|
+
smiles = [raw] if isinstance(raw, str) else list(raw)
|
|
22
|
+
if not smiles:
|
|
23
|
+
raise ValueError("no molecules given")
|
|
24
|
+
parts = [featurize(s, self._tokenizer, self.manifest.meta["max_len"]) for s in smiles]
|
|
25
|
+
n, d = max(len(p[1]) for p in parts), parts[0][1].shape[1]
|
|
26
|
+
atoms, adj, mask = np.zeros((len(parts), n, d), np.float32), np.zeros((len(parts), n, n), np.float32), np.zeros((len(parts), n), np.float32)
|
|
27
|
+
for i, (_, a, ad) in enumerate(parts):
|
|
28
|
+
atoms[i, : len(a)], adj[i, : len(a), : len(a)], mask[i, : len(a)] = a, ad, 1
|
|
29
|
+
self._single = isinstance(raw, str)
|
|
30
|
+
return {"tokens": np.stack([p[0] for p in parts]), "atoms": atoms, "adj": adj, "atom_mask": mask}
|
|
31
|
+
|
|
32
|
+
def finish(self, results):
|
|
33
|
+
return results[0] if self._single else results
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@register("chem_mol_embedding")
|
|
37
|
+
class MolecularEmbedding(MoleculePipeline):
|
|
38
|
+
"""A 256-dimensional vector per molecule."""
|
|
39
|
+
|
|
40
|
+
def postprocess(self, outputs):
|
|
41
|
+
return self.finish([MoleculeEmbedding(vector=v) for v in outputs[0]])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@register("chem_logp")
|
|
45
|
+
@register("chem_solubility")
|
|
46
|
+
class Regression(MoleculePipeline):
|
|
47
|
+
"""``properties`` has one entry, in real units: ``logp`` or ``logS``."""
|
|
48
|
+
|
|
49
|
+
def postprocess(self, outputs):
|
|
50
|
+
meta = self.manifest.meta
|
|
51
|
+
values = outputs[0][:, 0] * meta["target_std"] + meta["target_mean"]
|
|
52
|
+
return self.finish([PropertyPrediction(properties={meta["target"]: float(v)}) for v in values])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@register("chem_toxicity")
|
|
56
|
+
class Toxicity(MoleculePipeline):
|
|
57
|
+
"""``properties`` holds a probability for each of the 12 Tox21 assays and ClinTox (`CT_TOX`)."""
|
|
58
|
+
|
|
59
|
+
def postprocess(self, outputs):
|
|
60
|
+
tasks = self.manifest.meta["tasks"]
|
|
61
|
+
return self.finish([PropertyPrediction(properties={t: float(p) for t, p in zip(tasks, row)}) for row in outputs[0]])
|