@openfluke/welvet 0.2.0 → 0.74.0

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.
package/README.md CHANGED
@@ -1,399 +1,109 @@
1
- # @openfluke/welvet - LOOM TypeScript/WASM Bindings
2
-
3
- **Wrapper for Embedding Loom Via External (WASM) Toolchain**
4
-
5
- High-performance neural network library with **full training in browser/Node.js** via WebAssembly. Zero external dependencies—just import and go.
6
-
7
- ## Framework Comparison
8
-
9
- | Feature Category | Feature | **Loom/welvet** | **TensorFlow.js** | **Brain.js** | **ONNX.js** | **Candle (WASM)** |
10
- | :--- | :--- | :---: | :---: | :---: | :---: | :---: |
11
- | **Core** | **Runtime** | WASM (Pure Go) | JS + WebGL | Pure JS | WASM | WASM (Rust) |
12
- | | **Runtime Dependency** | **None** | Heavy | Light | Light | None |
13
- | **Loading** | **Safetensors** | **Native** | | | ❌ | ✅ |
14
- | | **Structure Inference** | **Auto-Detect** | | | | ❌ |
15
- | **Training** | **Browser Training** | ✅ **Full** | ✅ (Slow) | ✅ | ❌ | ✅ |
16
- | | **Neural Tweening** | ✅ **Hybrid Engine** | ❌ | ❌ | ❌ | ❌ |
17
- | | **LR Schedulers** | ✅ **7 Types** | ✅ | ⚠️ | ❌ | ✅ |
18
- | **Layer Support** | **Dense (MLP)** | ✅ | ✅ | ✅ | ✅ | ✅ |
19
- | | **Conv1D/2D** | ✅ **Native** | ✅ | ❌ | ✅ | ✅ |
20
- | | **RNN / LSTM** | ✅ **Full Gate** | ✅ | ✅ | ✅ | ✅ |
21
- | | **Transformer (MHA)** | ✅ (Explicit) | ✅ | ❌ | ✅ | ✅ |
22
- | | **Parallel / MoE** | ✅ **Structure** | ❌ (Manual) | ❌ | ❌ | ❌ |
23
- | | **Sequential Layers** | ✅ **Native** | ⚠️ | ⚠️ | ❌ | ⚠️ |
24
- | **Advanced** | **Step-Based Forward** | ✅ **Unique** | ❌ | ❌ | ❌ | ❌ |
25
- | | **Stitch Layers** | ✅ **Native** | ❌ | ❌ | ❌ | ❌ |
26
- | | **K-Means / Stats** | ✅ **Parallel** | ❌ | ❌ | ❌ | ❌ |
27
- | | **Cross-Lang ABI** | ✅ **Universal** | ❌ | ❌ | ❌ | ⚠️ |
28
- | **Streaming** | **LLM Streaming** | ✅ | ✅ | ❌ | ❌ | ✅ |
29
- | | **Pure Go Tokenizer** | ✅ | ❌ | ❌ | ❌ | ❌ |
30
-
31
- For detailed comparison, see [`docs/loom_assessment_comparison.md`](../docs/loom_assessment_comparison.md).
32
-
33
- ## 🌍 Cross-Ecosystem Compatibility
34
-
35
- Models trained in TypeScript can be loaded instantly in Python, C#, Go, or other WASM environments. **Bit-for-bit identical results** across all platforms.
36
-
37
- | Platform | Package | Install |
38
- |:---------|:--------|:--------|
39
- | **TypeScript/Node** | [NPM](https://www.npmjs.com/package/@openfluke/welvet) | `npm install @openfluke/welvet` |
40
- | **Python** | [PyPI](https://pypi.org/project/welvet/) | `pip install welvet` |
41
- | **C#/.NET** | [NuGet](https://www.nuget.org/packages/Welvet) | `dotnet add package Welvet` |
42
- | **Go** | [GitHub](https://github.com/openfluke/loom) | `go get github.com/openfluke/loom` |
43
-
44
- ### Key Strengths
45
-
46
- - **True Embeddability**: Single WASM binary. Works in Node.js and browsers with the same API.
47
- - **Hybrid Gradient/Geometric Engine**: "Neural Tweening" combines geometric gap-closing with backpropagation-guided momentum.
48
- - **Structural Parallelism**: Native support for Inception, ResNeXt, Siamese, and MoE architectures via `LayerParallel`.
49
- - **Native Mixed-Precision**: Generic tensor backend supports `int8`, `uint16`, and `float32`.
50
- - **Complete Evaluation Suite**: Deviation metrics, training milestones, and adaptation tracking.
51
- - **Network Telemetry**: Runtime introspection with `GetMethodsJSON()` and `ExtractNetworkBlueprint()`.
1
+ # @openfluke/welvet
2
+
3
+ **M-POLY-VTD AI Engine (Loom v0.74.0)** Isomorphic TypeScript/WASM library for building, training, and evolving neural networks with 21 numerical types, WebGPU acceleration, and DNA-based evolution.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@openfluke/welvet.svg)](https://www.npmjs.com/package/@openfluke/welvet)
6
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
7
+
8
+ ## Features
9
+
10
+ - **Isomorphic Architecture**: Runs seamlessly in Node.js, Bun, and the Browser (React/Frontend).
11
+ - **Multi-Precision Support**: Native support for 21 numerical types (FP64, FP32, FP16, BF16, FP8, INT8... all the way down to Binary/Ternary).
12
+ - **Hybrid Training**: standard Backprop, Target Propagation, and NEAT-style structural evolution in a single unified engine.
13
+ - **Hardware Acceleration**: WebGPU support for high-performance inference and training in the browser.
14
+ - **DNA Evolution**: Network "DNA" extraction and comparison for architectural analysis and genetic recombination.
52
15
 
53
16
  ## Installation
54
17
 
55
18
  ```bash
56
19
  npm install @openfluke/welvet
57
- ```
58
-
59
- **Using Bun:**
60
- ```bash
20
+ # or
61
21
  bun add @openfluke/welvet
62
22
  ```
63
23
 
64
24
  ## Quick Start
65
25
 
66
- ### 🎉 Simple API (Recommended)
26
+ ### 1. Initialization
67
27
 
68
- The simple API provides streamlined functions with **cross-platform consistency**:
28
+ The engine initializes automatically after a single call to `init()`. It detects whether it's running in Node.js, Bun, or the Browser and loads the appropriate WASM environment.
69
29
 
70
30
  ```typescript
71
- import { init, createNetworkFromJSON, loadLoomNetwork } from "@openfluke/welvet";
72
-
73
- // Initialize LOOM WASM
74
- await init();
31
+ import { init } from "@openfluke/welvet";
75
32
 
76
- // Create network from JSON config
77
- const config = {
78
- batch_size: 1,
79
- grid_rows: 1,
80
- grid_cols: 3,
81
- layers_per_cell: 1,
82
- layers: [
83
- { type: "dense", input_size: 8, output_size: 16, activation: "relu" },
84
- {
85
- type: "parallel",
86
- combine_mode: "grid_scatter",
87
- grid_output_rows: 3, grid_output_cols: 1, grid_output_layers: 1,
88
- grid_positions: [
89
- { branch_index: 0, target_row: 0, target_col: 0, target_layer: 0 },
90
- { branch_index: 1, target_row: 1, target_col: 0, target_layer: 0 },
91
- { branch_index: 2, target_row: 2, target_col: 0, target_layer: 0 },
92
- ],
93
- branches: [
94
- { type: "parallel", combine_mode: "add", branches: [
95
- { type: "dense", input_size: 16, output_size: 8, activation: "relu" },
96
- { type: "dense", input_size: 16, output_size: 8, activation: "gelu" },
97
- ]},
98
- { type: "lstm", input_size: 16, hidden_size: 8, seq_length: 1 },
99
- { type: "rnn", input_size: 16, hidden_size: 8, seq_length: 1 },
100
- ],
101
- },
102
- { type: "dense", input_size: 24, output_size: 2, activation: "sigmoid" },
103
- ],
104
- };
105
-
106
- const network = createNetworkFromJSON(JSON.stringify(config));
107
-
108
- // Training
109
- const batches = [
110
- { Input: [0.2, 0.2, 0.2, 0.2, 0.8, 0.8, 0.8, 0.8], Target: [1.0, 0.0] },
111
- { Input: [0.9, 0.9, 0.9, 0.9, 0.1, 0.1, 0.1, 0.1], Target: [0.0, 1.0] },
112
- ];
113
-
114
- const trainingConfig = {
115
- Epochs: 800,
116
- LearningRate: 0.15,
117
- LossType: "mse",
118
- GradientClip: 1.0,
119
- };
120
-
121
- network.Train(JSON.stringify([batches, trainingConfig]));
122
-
123
- // Forward pass
124
- const [output] = network.ForwardCPU(JSON.stringify([[0.2, 0.2, 0.2, 0.2, 0.8, 0.8, 0.8, 0.8]]));
125
- console.log("Output:", JSON.parse(output)); // [0.95, 0.05]
126
-
127
- // Save/Load
128
- const [modelJSON] = network.SaveModelToString(JSON.stringify(["my_model"]));
129
- const loadedNetwork = loadLoomNetwork(modelJSON, "my_model");
33
+ await init(); // Just works™
130
34
  ```
131
35
 
132
- **Simple API Functions:**
133
-
134
- | Function | Description |
135
- |:---------|:------------|
136
- | `createNetworkFromJSON(config)` | Create network from JSON |
137
- | `loadLoomNetwork(json, id)` | Load saved model |
138
- | `network.ForwardCPU(input)` | Forward pass |
139
- | `network.BackwardCPU(gradients)` | Backward pass |
140
- | `network.Train(params)` | Train network |
141
- | `network.SaveModelToString(id)` | Save to JSON string |
142
- | `network.EvaluateNetwork(params)` | Evaluate with metrics |
36
+ > [!TIP]
37
+ > In browser environments, if your assets are served from a non-standard path, you can optionally pass a custom URL: `await init("/custom/path/to/main.wasm")`.
143
38
 
144
- ### Stepping API - Fine-Grained Execution Control
145
-
146
- Execute networks one step at a time for online learning:
39
+ ### 2. Create a Network
147
40
 
148
41
  ```typescript
149
- import { init, createNetwork, StepState } from "@openfluke/welvet";
150
-
151
- await init();
42
+ import { createNetwork, DType } from "@openfluke/welvet";
152
43
 
153
- const network = createNetwork({
154
- batch_size: 1,
44
+ const net = createNetwork({
155
45
  layers: [
156
- { type: "dense", input_height: 4, output_height: 8, activation: "relu" },
157
- { type: "lstm", input_size: 8, hidden_size: 12, seq_length: 1 },
158
- { type: "dense", input_height: 12, output_height: 3, activation: "softmax" }
46
+ { type: "Dense", input_height: 784, output_height: 256, activation: "ReLU", dtype: DType.FLOAT32 },
47
+ { type: "Dense", input_height: 256, output_height: 10, activation: "Linear", dtype: DType.FLOAT16 }
159
48
  ]
160
49
  });
161
50
 
162
- // Initialize stepping state
163
- const state: StepState = network.createStepState(4);
164
-
165
- // Training loop - update weights after EACH step
166
- for (let step = 0; step < 100000; step++) {
167
- state.setInput(new Float32Array([0.1, 0.2, 0.1, 0.3]));
168
- state.stepForward();
169
- const output = state.getOutput();
170
-
171
- // Backward pass
172
- const gradients = output.map((o, i) => o - target[i]);
173
- state.stepBackward(gradients);
174
-
175
- // Update weights immediately
176
- network.ApplyGradients(JSON.stringify([learningRate]));
177
- }
51
+ const input = new Float32Array(784).fill(0.5);
52
+ const output = net.sequentialForward(input);
53
+ console.log("Prediction:", output);
178
54
  ```
179
55
 
180
- ### 🧠 Neural Tweening API - Gradient-Free Learning
181
-
182
- Direct weight adjustment without backpropagation:
56
+ ### 3. Training
183
57
 
184
58
  ```typescript
185
- import { init, createNetwork, TweenState } from "@openfluke/welvet";
186
-
187
- await init();
188
-
189
- const network = createNetwork(config);
190
-
191
- // Create tween state (with optional chain rule)
192
- const tweenState: TweenState = network.createTweenState(true); // useChainRule=true
193
-
194
- // Training loop - direct weight updates
195
- for (let step = 0; step < 10000; step++) {
196
- const loss = tweenState.TweenStep(
197
- new Float32Array([0.1, 0.2, 0.3, 0.4]),
198
- 1, // targetClass
199
- 4, // outputSize
200
- 0.02 // learningRate
201
- );
202
- }
203
- ```
204
-
205
- ### 📊 Adaptation Benchmark
206
-
207
- Run the full multi-architecture adaptation benchmark:
208
-
209
- ```bash
210
- cd example
211
- bun run test18_adaptation.ts
212
- ```
213
-
214
- Tests **5 architectures × 3 depths × 5 training modes** (75 tests total):
215
- - **Architectures:** Dense, Conv2D, RNN, LSTM, Attention
216
- - **Depths:** 3, 5, 9 layers
217
- - **Modes:** NormalBP, StepBP, Tween, TweenChain, StepTweenChain
218
-
219
- ## Complete Test Suite
220
-
221
- The `universal_test.ts` example demonstrates all framework capabilities:
59
+ import { trainNetwork } from "@openfluke/welvet";
222
60
 
223
- ```bash
224
- cd example
225
- bun run universal_test.ts
226
- ```
227
-
228
- **Test Coverage:**
229
- - ✅ 12 Layer Types × 6 Data Types (72 tests)
230
- - ✅ Network Grafting
231
- - ✅ K-Means Clustering & Correlation Analysis
232
- - ✅ Optimizers (SGD, AdamW, RMSprop)
233
- - ✅ Ensemble Features
234
- - ✅ Observer Pattern (Adaptation Tracking)
235
- - ✅ Introspection API
236
- - ✅ Step & Tween API
237
- - ✅ Advanced Layers (Embedding, Residual)
238
-
239
- See [`example/universal_test.ts`](./example/universal_test.ts) for the complete test implementation.
240
-
241
- ## Layer Types
242
-
243
- | Layer | Type String | Description |
244
- |:------|:------------|:------------|
245
- | Dense | `dense` | Fully connected layer |
246
- | LSTM | `lstm` | Long Short-Term Memory |
247
- | RNN | `rnn` | Recurrent Neural Network |
248
- | GRU | `gru` | Gated Recurrent Unit |
249
- | Conv2D | `conv2d` | 2D Convolution |
250
- | Conv1D | `conv1d` | 1D Convolution |
251
- | Multi-Head Attention | `multi_head_attention` | Transformer attention |
252
- | LayerNorm | `layer_norm` | Layer normalization |
253
- | RMSNorm | `rms_norm` | RMS normalization |
254
- | SwiGLU | `swiglu` | SwiGLU activation layer |
255
- | Softmax | `softmax` | Softmax classification |
256
- | Embedding | `embedding` | Token embedding |
257
- | Parallel | `parallel` | Branching with combine modes |
258
- | Sequential | `sequential` | Grouped sub-layers |
259
-
260
- **Parallel Combine Modes:** `add`, `concat`, `multiply`, `average`, `grid_scatter`, `filter`
261
-
262
- ## Activation Functions
263
-
264
- `relu`, `sigmoid`, `tanh`, `softmax`, `gelu`, `swish`, `mish`, `leaky_relu`, `elu`, `selu`, `linear`
265
-
266
- ## API Reference
267
-
268
- ### Initialization
269
-
270
- ```typescript
271
- import { init, initBrowser, createNetwork, createNetworkFromJSON } from "@openfluke/welvet";
272
-
273
- // Node.js
274
- await init();
61
+ const batches = [
62
+ { input: [0.1, 0.2, ...], target: [1, 0, ...] },
63
+ ];
275
64
 
276
- // Browser
277
- await initBrowser();
65
+ const result = trainNetwork(net, batches, 10, 0.001);
66
+ console.log("Final Loss:", result.final_loss);
278
67
  ```
279
68
 
280
- ### Network Methods
281
-
282
- All Network methods follow the WASM calling convention:
283
- - **Input:** JSON string of an array of parameters
284
- - **Return:** JSON string of an array of results
69
+ ### 4. NEAT Evolution
285
70
 
286
71
  ```typescript
287
- // Method with no parameters
288
- const info = network.GetNetworkInfo(JSON.stringify([]));
289
-
290
- // Method with parameters
291
- const result = network.Train(JSON.stringify([batches, config]));
292
-
293
- // Save model
294
- const saved = network.SaveModelToString(JSON.stringify(["my-model"]));
295
- ```
72
+ import { createNEATPopulation } from "@openfluke/welvet";
296
73
 
297
- **Available Methods:**
298
-
299
- | Method | Parameters | Description |
300
- |:-------|:-----------|:------------|
301
- | `ForwardCPU` | `[inputs]` | CPU forward pass |
302
- | `ForwardGPU` | `[inputs]` | GPU forward pass |
303
- | `BackwardCPU` | `[gradients]` | CPU backward pass |
304
- | `Train` | `[batches, config]` | Train network |
305
- | `SaveModelToString` | `["modelID"]` | Save to JSON |
306
- | `GetWeights` | `[row, col, layer]` | Get layer weights |
307
- | `SetWeights` | `[row, col, layer, weights]` | Set layer weights |
308
- | `GetBiases` | `[row, col, layer]` | Get layer biases |
309
- | `SetBiases` | `[row, col, layer, biases]` | Set layer biases |
310
- | `GetNetworkInfo` | `[]` | Get network info |
311
- | `GetTotalParameters` | `[]` | Get parameter count |
312
- | `Clone` | `[]` | Clone network |
313
- | `TotalLayers` | `[]` | Get total layer count |
314
-
315
- ### Statistical Tools
74
+ const population = createNEATPopulation(net, 100);
75
+ const fitnesses = new Array(100).fill(0).map(() => Math.random());
316
76
 
317
- ```typescript
318
- import welvet from "@openfluke/welvet";
319
-
320
- // K-Means Clustering
321
- const data = [[1, 1], [1.1, 1.1], [5, 5], [5.1, 5.1]];
322
- const result = welvet.kmeans(data, 2, 100);
323
- console.log(`Centroids: ${result.centroids}`);
324
- console.log(`Silhouette Score: ${result.silhouette_score}`);
325
-
326
- // Correlation Matrix
327
- const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
328
- const corr = welvet.correlation(matrix);
329
- console.log(`Pearson: ${corr.pearson}`);
77
+ population.evolveWithFitnesses(fitnesses);
78
+ const bestNet = population.best();
79
+ console.log("Best Fitness:", population.bestFitness());
330
80
  ```
331
81
 
332
- ### Network Grafting
82
+ ## Testing & Benchmarks
333
83
 
334
- Combine multiple trained networks:
84
+ The package includes a built-in TypeScript testing suite suitable for both CI and environment verification.
335
85
 
336
- ```typescript
337
- const h1 = welvet.createKHandle(config);
338
- const h2 = welvet.createKHandle(config);
86
+ ### Run tests in Node.js:
339
87
 
340
- const result = welvet.graft([h1, h2], "concat");
341
- console.log(`Grafted: ${result.num_branches} branches`);
88
+ ```bash
89
+ npm test
342
90
  ```
343
91
 
344
- ## Examples
345
-
92
+ Or individual suites:
346
93
  ```bash
347
- cd example
348
-
349
- # Grid Scatter Multi-Agent
350
- bun run grid-scatter.ts
351
-
352
- # Stepping Training (LSTM)
353
- bun run step_train_v3.ts
354
-
355
- # Adaptation Benchmark (75 tests)
356
- bun run test18_adaptation.ts
357
-
358
- # Full Test Suite (77 tests)
359
- bun run universal_test.ts
94
+ npm run test:cabi # Check WASM exports and functional smoke tests
95
+ npm run test:bench # Run layer-by-layer performance benchmarks
360
96
  ```
361
97
 
362
- ## TypeScript Types
98
+ ### Integrate tests into Frontend/React:
363
99
 
364
100
  ```typescript
365
- interface NetworkConfig {
366
- batch_size: number;
367
- grid_rows?: number;
368
- grid_cols?: number;
369
- layers_per_cell?: number;
370
- layers: LayerConfig[];
371
- dtype?: "float32" | "float64" | "int32" | "int16" | "int8" | "uint8";
372
- }
373
-
374
- interface TrainingConfig {
375
- Epochs: number;
376
- LearningRate: number;
377
- LossType?: string;
378
- Verbose?: boolean;
379
- UseGPU?: boolean;
380
- GradientClip?: number;
381
- }
382
-
383
- interface TrainingBatch {
384
- Input: number[];
385
- Target: number[];
386
- }
101
+ import { runVerify } from "@openfluke/welvet/tests/cabi_verify";
102
+
103
+ // Run benchmarks or verification logic directly in your app's lifecycle
104
+ await runVerify();
387
105
  ```
388
106
 
389
107
  ## License
390
108
 
391
109
  Apache-2.0
392
-
393
- ## Links
394
-
395
- - **GitHub**: [github.com/openfluke/loom](https://github.com/openfluke/loom)
396
- - **NPM**: [@openfluke/welvet](https://www.npmjs.com/package/@openfluke/welvet)
397
- - **PyPI**: [welvet](https://pypi.org/project/welvet/)
398
- - **NuGet**: [Welvet](https://www.nuget.org/packages/Welvet)
399
- - **Documentation**: [`docs/loom_assessment_comparison.md`](../docs/loom_assessment_comparison.md)