dual-cbf-compiler 0.1.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.
@@ -0,0 +1,235 @@
1
+ Metadata-Version: 2.4
2
+ Name: dual_cbf_compiler
3
+ Version: 0.1.0
4
+ Summary: Ahead-of-time compiler that translates trained neural control barrier functions into bare-metal C++ headers evaluating exact Lie derivatives via dual algebra, with zero dynamic memory allocation on embedded targets.
5
+ Home-page: https://github.com/mkamaldar/dual_cbf_compiler
6
+ Author: Mohammadreza Kamaldar
7
+ Author-email: mkamaldar@southalabama.edu
8
+ License: MIT
9
+ Keywords: control-barrier-functions,neural-networks,automatic-differentiation,embedded-systems,code-generation,dual-numbers,lie-derivatives,real-time,safety-critical
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: C++
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Classifier: Topic :: Software Development :: Compilers
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ Requires-Dist: numpy>=1.21
26
+ Provides-Extra: torch
27
+ Requires-Dist: torch>=1.13; extra == "torch"
28
+ Provides-Extra: onnx
29
+ Requires-Dist: onnx>=1.12; extra == "onnx"
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7.0; extra == "test"
32
+ Requires-Dist: torch>=1.13; extra == "test"
33
+ Requires-Dist: onnx>=1.12; extra == "test"
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest>=7.0; extra == "dev"
36
+ Requires-Dist: torch>=1.13; extra == "dev"
37
+ Requires-Dist: onnx>=1.12; extra == "dev"
38
+ Requires-Dist: ruff; extra == "dev"
39
+ Requires-Dist: mypy; extra == "dev"
40
+ Dynamic: author
41
+ Dynamic: author-email
42
+ Dynamic: classifier
43
+ Dynamic: description
44
+ Dynamic: description-content-type
45
+ Dynamic: home-page
46
+ Dynamic: keywords
47
+ Dynamic: license
48
+ Dynamic: provides-extra
49
+ Dynamic: requires-dist
50
+ Dynamic: requires-python
51
+ Dynamic: summary
52
+
53
+ # dual_cbf_compiler
54
+
55
+ Ahead-of-time compiler that translates trained neural Control Barrier Functions
56
+ into bare-metal C++ headers evaluating exact Lie derivatives via dual algebra.
57
+ The generated code performs zero dynamic memory allocation and is suitable for
58
+ deployment on resource-constrained microcontrollers running kilohertz-rate
59
+ safety filters.
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ pip install -e ".[test]"
65
+ ```
66
+
67
+ ## Recommended workflow: ONNX-first
68
+
69
+ The cleanest path is to **export your trained PyTorch model to ONNX**. ONNX
70
+ captures the network topology along with the weights, so no manual architecture
71
+ declaration is required:
72
+
73
+ ```python
74
+ import torch
75
+ torch.onnx.export(
76
+ model,
77
+ sample_input,
78
+ "model.onnx",
79
+ input_names=["x"],
80
+ output_names=["h"],
81
+ opset_version=14,
82
+ )
83
+ ```
84
+
85
+ then either
86
+
87
+ ```bash
88
+ dual-cbf-compile model.onnx -o dual_cbf.h --relative-degree 1
89
+ ```
90
+
91
+ or programmatically
92
+
93
+ ```python
94
+ from dual_cbf_compiler import parse_onnx, emit_cpp_header
95
+
96
+ network = parse_onnx("model.onnx")
97
+ header = emit_cpp_header(network, relative_degree=1)
98
+ open("dual_cbf.h", "w").write(header)
99
+ ```
100
+
101
+ ## Direct PyTorch ingestion (programmatic, recommended)
102
+
103
+ If you have an in-memory `torch.nn.Sequential` whose modules describe the
104
+ topology, parse it directly — no string declaration required:
105
+
106
+ ```python
107
+ import torch.nn as nn
108
+ from dual_cbf_compiler import parse_pytorch, emit_cpp_header
109
+
110
+ model = nn.Sequential(
111
+ nn.Linear(4, 32), nn.ReLU(),
112
+ nn.Linear(32, 32), nn.ReLU(),
113
+ nn.Linear(32, 1),
114
+ )
115
+ # (load trained weights into model here)
116
+
117
+ network = parse_pytorch(model) # relative_degree=1 by default
118
+ header = emit_cpp_header(network, relative_degree=1)
119
+ open("dual_cbf.h", "w").write(header)
120
+ ```
121
+
122
+ ## PyTorch state_dict from the command line (fallback only)
123
+
124
+ PyTorch state_dicts (`.pt`/`.pth`) only save tensor weights, not the
125
+ computational graph, so the CLI must be told the topology via `--torch-arch`.
126
+ **This is error-prone — a typo silently maps weights to the wrong dimensions.**
127
+ Prefer the ONNX export path above.
128
+
129
+ ```bash
130
+ # Only if ONNX export is unavailable
131
+ dual-cbf-compile model.pt -o dual_cbf.h \
132
+ --torch-arch "4,relu,32,relu,32,linear,1"
133
+ ```
134
+
135
+ ## Use the generated C++ header
136
+
137
+ ```cpp
138
+ #include "dual_cbf.h"
139
+
140
+ float x[4] = {/* state */};
141
+ float f[4] = {/* drift */};
142
+
143
+ // IMPORTANT: G(x) is ROW-MAJOR with shape (n x m).
144
+ // Element G(i, j) lives at G[i * m + j].
145
+ // If you keep G as a 2D C array float G2D[4][2], populate the flat
146
+ // layout as:
147
+ // for (int i = 0; i < 4; ++i)
148
+ // for (int j = 0; j < 2; ++j)
149
+ // G[i * 2 + j] = G2D[i][j];
150
+ float G[4 * 2] = {
151
+ /* row 0 */ 0.0f, 0.0f,
152
+ /* row 1 */ 0.0f, 0.0f,
153
+ /* row 2 */ 0.0f, 0.4f,
154
+ /* row 3 */ 1.0f, 0.0f,
155
+ };
156
+
157
+ float h, Lf, Lg[2];
158
+ dual_cbf::evaluate_cbf(x, f, G, /*m=*/2, &h, &Lf, Lg);
159
+
160
+ // CBF QP constraint: L_f h + L_G h * u >= -alpha(h)
161
+ ```
162
+
163
+ The generated header repeats this row-major layout reminder in its file-level
164
+ comment so the convention is impossible to miss at the call site.
165
+
166
+ ## Relative-degree-2 (hyper-dual)
167
+
168
+ For mechanical systems with acceleration inputs:
169
+
170
+ ```python
171
+ network = parse_onnx("softplus_model.onnx", relative_degree=2)
172
+ header = emit_cpp_header(network, relative_degree=2)
173
+ ```
174
+
175
+ ```cpp
176
+ float L2f, LgLf[m];
177
+ dual_cbf::evaluate_cbf_2nd_order(x, f, G, Df_f, Df_G, m, &L2f, LgLf);
178
+ ```
179
+
180
+ `Df_f` is the user-supplied Jacobian-vector product `f'(x) f(x)` (length `n`),
181
+ and `Df_G` is the row-major Jacobian-vector product `f'(x) G(x)` (shape `n×m`).
182
+
183
+ **ReLU is rejected for relative_degree=2.** ReLU's second derivative vanishes
184
+ almost everywhere, so the Hessian contribution to `L_f^2 h_theta` and
185
+ `L_{col_j(G)} L_f h_theta` would be silently lost. Both `parse_pytorch` and
186
+ `parse_onnx` raise a `ValueError` at parse time if a ReLU layer is detected
187
+ and `relative_degree=2` was requested. Retrain with **Softplus**, **Tanh**,
188
+ or **Sigmoid** instead.
189
+
190
+ ## Verify
191
+
192
+ ```bash
193
+ # Numpy-only verification (no torch needed)
194
+ python3 numpy_verify.py
195
+ python3 numpy_verify_2nd.py
196
+
197
+ # Full suite (requires torch)
198
+ pytest -v dual_cbf_compiler/verify.py
199
+ ```
200
+
201
+ The pytest suite builds random PyTorch networks, evaluates Lie derivatives via
202
+ `torch.autograd`, compiles the generated C++ via `g++`, runs the binary, and
203
+ asserts agreement to single-precision machine epsilon.
204
+
205
+ ## Design
206
+
207
+ * **Zero dynamic allocation.** All weights and biases are embedded as
208
+ `static const float` arrays. A single shared static scratch buffer of
209
+ `2 * max(n_i)` floats (relative-degree 1) or `4 * max(n_i)` floats
210
+ (relative-degree 2) is destructively overwritten as the forward pass
211
+ advances layer by layer.
212
+ * **Forward-only.** The chain rule is collapsed into a memoryless forward
213
+ recurrence by encoding the system state as the real part and a vector
214
+ field as the dual part of an input dual vector. No reverse-mode AD,
215
+ no computational graph.
216
+ * **Algebraic mode selection.** `relative_degree=1` emits standard dual
217
+ algebra (eps^2 = 0). `relative_degree=2` emits hyper-dual arithmetic
218
+ with cross term eps_12, allowing exact extraction of the second-order
219
+ Lie derivatives required for acceleration-controlled mechanical systems.
220
+ * **Hard guards on common footguns.** ReLU + relative_degree=2 is a
221
+ `ValueError`, not a passive warning. The CLI declines to silently map
222
+ weights to the wrong topology — when `--torch-arch` and the state_dict
223
+ disagree, it refuses with a hint to use ONNX.
224
+
225
+ ## Layout
226
+
227
+ ```
228
+ dual_cbf_compiler/
229
+ ir.py — Internal representation (LinearLayer, ActivationLayer)
230
+ parser.py — parse_pytorch, parse_onnx (both accept relative_degree)
231
+ emitter.py — emit_cpp_header
232
+ verify.py — Pytest suite (PyTorch autograd vs g++-compiled binary)
233
+ cli.py — dual-cbf-compile entry point
234
+ setup.py
235
+ ```
@@ -0,0 +1,183 @@
1
+ # dual_cbf_compiler
2
+
3
+ Ahead-of-time compiler that translates trained neural Control Barrier Functions
4
+ into bare-metal C++ headers evaluating exact Lie derivatives via dual algebra.
5
+ The generated code performs zero dynamic memory allocation and is suitable for
6
+ deployment on resource-constrained microcontrollers running kilohertz-rate
7
+ safety filters.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install -e ".[test]"
13
+ ```
14
+
15
+ ## Recommended workflow: ONNX-first
16
+
17
+ The cleanest path is to **export your trained PyTorch model to ONNX**. ONNX
18
+ captures the network topology along with the weights, so no manual architecture
19
+ declaration is required:
20
+
21
+ ```python
22
+ import torch
23
+ torch.onnx.export(
24
+ model,
25
+ sample_input,
26
+ "model.onnx",
27
+ input_names=["x"],
28
+ output_names=["h"],
29
+ opset_version=14,
30
+ )
31
+ ```
32
+
33
+ then either
34
+
35
+ ```bash
36
+ dual-cbf-compile model.onnx -o dual_cbf.h --relative-degree 1
37
+ ```
38
+
39
+ or programmatically
40
+
41
+ ```python
42
+ from dual_cbf_compiler import parse_onnx, emit_cpp_header
43
+
44
+ network = parse_onnx("model.onnx")
45
+ header = emit_cpp_header(network, relative_degree=1)
46
+ open("dual_cbf.h", "w").write(header)
47
+ ```
48
+
49
+ ## Direct PyTorch ingestion (programmatic, recommended)
50
+
51
+ If you have an in-memory `torch.nn.Sequential` whose modules describe the
52
+ topology, parse it directly — no string declaration required:
53
+
54
+ ```python
55
+ import torch.nn as nn
56
+ from dual_cbf_compiler import parse_pytorch, emit_cpp_header
57
+
58
+ model = nn.Sequential(
59
+ nn.Linear(4, 32), nn.ReLU(),
60
+ nn.Linear(32, 32), nn.ReLU(),
61
+ nn.Linear(32, 1),
62
+ )
63
+ # (load trained weights into model here)
64
+
65
+ network = parse_pytorch(model) # relative_degree=1 by default
66
+ header = emit_cpp_header(network, relative_degree=1)
67
+ open("dual_cbf.h", "w").write(header)
68
+ ```
69
+
70
+ ## PyTorch state_dict from the command line (fallback only)
71
+
72
+ PyTorch state_dicts (`.pt`/`.pth`) only save tensor weights, not the
73
+ computational graph, so the CLI must be told the topology via `--torch-arch`.
74
+ **This is error-prone — a typo silently maps weights to the wrong dimensions.**
75
+ Prefer the ONNX export path above.
76
+
77
+ ```bash
78
+ # Only if ONNX export is unavailable
79
+ dual-cbf-compile model.pt -o dual_cbf.h \
80
+ --torch-arch "4,relu,32,relu,32,linear,1"
81
+ ```
82
+
83
+ ## Use the generated C++ header
84
+
85
+ ```cpp
86
+ #include "dual_cbf.h"
87
+
88
+ float x[4] = {/* state */};
89
+ float f[4] = {/* drift */};
90
+
91
+ // IMPORTANT: G(x) is ROW-MAJOR with shape (n x m).
92
+ // Element G(i, j) lives at G[i * m + j].
93
+ // If you keep G as a 2D C array float G2D[4][2], populate the flat
94
+ // layout as:
95
+ // for (int i = 0; i < 4; ++i)
96
+ // for (int j = 0; j < 2; ++j)
97
+ // G[i * 2 + j] = G2D[i][j];
98
+ float G[4 * 2] = {
99
+ /* row 0 */ 0.0f, 0.0f,
100
+ /* row 1 */ 0.0f, 0.0f,
101
+ /* row 2 */ 0.0f, 0.4f,
102
+ /* row 3 */ 1.0f, 0.0f,
103
+ };
104
+
105
+ float h, Lf, Lg[2];
106
+ dual_cbf::evaluate_cbf(x, f, G, /*m=*/2, &h, &Lf, Lg);
107
+
108
+ // CBF QP constraint: L_f h + L_G h * u >= -alpha(h)
109
+ ```
110
+
111
+ The generated header repeats this row-major layout reminder in its file-level
112
+ comment so the convention is impossible to miss at the call site.
113
+
114
+ ## Relative-degree-2 (hyper-dual)
115
+
116
+ For mechanical systems with acceleration inputs:
117
+
118
+ ```python
119
+ network = parse_onnx("softplus_model.onnx", relative_degree=2)
120
+ header = emit_cpp_header(network, relative_degree=2)
121
+ ```
122
+
123
+ ```cpp
124
+ float L2f, LgLf[m];
125
+ dual_cbf::evaluate_cbf_2nd_order(x, f, G, Df_f, Df_G, m, &L2f, LgLf);
126
+ ```
127
+
128
+ `Df_f` is the user-supplied Jacobian-vector product `f'(x) f(x)` (length `n`),
129
+ and `Df_G` is the row-major Jacobian-vector product `f'(x) G(x)` (shape `n×m`).
130
+
131
+ **ReLU is rejected for relative_degree=2.** ReLU's second derivative vanishes
132
+ almost everywhere, so the Hessian contribution to `L_f^2 h_theta` and
133
+ `L_{col_j(G)} L_f h_theta` would be silently lost. Both `parse_pytorch` and
134
+ `parse_onnx` raise a `ValueError` at parse time if a ReLU layer is detected
135
+ and `relative_degree=2` was requested. Retrain with **Softplus**, **Tanh**,
136
+ or **Sigmoid** instead.
137
+
138
+ ## Verify
139
+
140
+ ```bash
141
+ # Numpy-only verification (no torch needed)
142
+ python3 numpy_verify.py
143
+ python3 numpy_verify_2nd.py
144
+
145
+ # Full suite (requires torch)
146
+ pytest -v dual_cbf_compiler/verify.py
147
+ ```
148
+
149
+ The pytest suite builds random PyTorch networks, evaluates Lie derivatives via
150
+ `torch.autograd`, compiles the generated C++ via `g++`, runs the binary, and
151
+ asserts agreement to single-precision machine epsilon.
152
+
153
+ ## Design
154
+
155
+ * **Zero dynamic allocation.** All weights and biases are embedded as
156
+ `static const float` arrays. A single shared static scratch buffer of
157
+ `2 * max(n_i)` floats (relative-degree 1) or `4 * max(n_i)` floats
158
+ (relative-degree 2) is destructively overwritten as the forward pass
159
+ advances layer by layer.
160
+ * **Forward-only.** The chain rule is collapsed into a memoryless forward
161
+ recurrence by encoding the system state as the real part and a vector
162
+ field as the dual part of an input dual vector. No reverse-mode AD,
163
+ no computational graph.
164
+ * **Algebraic mode selection.** `relative_degree=1` emits standard dual
165
+ algebra (eps^2 = 0). `relative_degree=2` emits hyper-dual arithmetic
166
+ with cross term eps_12, allowing exact extraction of the second-order
167
+ Lie derivatives required for acceleration-controlled mechanical systems.
168
+ * **Hard guards on common footguns.** ReLU + relative_degree=2 is a
169
+ `ValueError`, not a passive warning. The CLI declines to silently map
170
+ weights to the wrong topology — when `--torch-arch` and the state_dict
171
+ disagree, it refuses with a hint to use ONNX.
172
+
173
+ ## Layout
174
+
175
+ ```
176
+ dual_cbf_compiler/
177
+ ir.py — Internal representation (LinearLayer, ActivationLayer)
178
+ parser.py — parse_pytorch, parse_onnx (both accept relative_degree)
179
+ emitter.py — emit_cpp_header
180
+ verify.py — Pytest suite (PyTorch autograd vs g++-compiled binary)
181
+ cli.py — dual-cbf-compile entry point
182
+ setup.py
183
+ ```
@@ -0,0 +1,235 @@
1
+ Metadata-Version: 2.4
2
+ Name: dual_cbf_compiler
3
+ Version: 0.1.0
4
+ Summary: Ahead-of-time compiler that translates trained neural control barrier functions into bare-metal C++ headers evaluating exact Lie derivatives via dual algebra, with zero dynamic memory allocation on embedded targets.
5
+ Home-page: https://github.com/mkamaldar/dual_cbf_compiler
6
+ Author: Mohammadreza Kamaldar
7
+ Author-email: mkamaldar@southalabama.edu
8
+ License: MIT
9
+ Keywords: control-barrier-functions,neural-networks,automatic-differentiation,embedded-systems,code-generation,dual-numbers,lie-derivatives,real-time,safety-critical
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: C++
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Classifier: Topic :: Software Development :: Compilers
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ Requires-Dist: numpy>=1.21
26
+ Provides-Extra: torch
27
+ Requires-Dist: torch>=1.13; extra == "torch"
28
+ Provides-Extra: onnx
29
+ Requires-Dist: onnx>=1.12; extra == "onnx"
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7.0; extra == "test"
32
+ Requires-Dist: torch>=1.13; extra == "test"
33
+ Requires-Dist: onnx>=1.12; extra == "test"
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest>=7.0; extra == "dev"
36
+ Requires-Dist: torch>=1.13; extra == "dev"
37
+ Requires-Dist: onnx>=1.12; extra == "dev"
38
+ Requires-Dist: ruff; extra == "dev"
39
+ Requires-Dist: mypy; extra == "dev"
40
+ Dynamic: author
41
+ Dynamic: author-email
42
+ Dynamic: classifier
43
+ Dynamic: description
44
+ Dynamic: description-content-type
45
+ Dynamic: home-page
46
+ Dynamic: keywords
47
+ Dynamic: license
48
+ Dynamic: provides-extra
49
+ Dynamic: requires-dist
50
+ Dynamic: requires-python
51
+ Dynamic: summary
52
+
53
+ # dual_cbf_compiler
54
+
55
+ Ahead-of-time compiler that translates trained neural Control Barrier Functions
56
+ into bare-metal C++ headers evaluating exact Lie derivatives via dual algebra.
57
+ The generated code performs zero dynamic memory allocation and is suitable for
58
+ deployment on resource-constrained microcontrollers running kilohertz-rate
59
+ safety filters.
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ pip install -e ".[test]"
65
+ ```
66
+
67
+ ## Recommended workflow: ONNX-first
68
+
69
+ The cleanest path is to **export your trained PyTorch model to ONNX**. ONNX
70
+ captures the network topology along with the weights, so no manual architecture
71
+ declaration is required:
72
+
73
+ ```python
74
+ import torch
75
+ torch.onnx.export(
76
+ model,
77
+ sample_input,
78
+ "model.onnx",
79
+ input_names=["x"],
80
+ output_names=["h"],
81
+ opset_version=14,
82
+ )
83
+ ```
84
+
85
+ then either
86
+
87
+ ```bash
88
+ dual-cbf-compile model.onnx -o dual_cbf.h --relative-degree 1
89
+ ```
90
+
91
+ or programmatically
92
+
93
+ ```python
94
+ from dual_cbf_compiler import parse_onnx, emit_cpp_header
95
+
96
+ network = parse_onnx("model.onnx")
97
+ header = emit_cpp_header(network, relative_degree=1)
98
+ open("dual_cbf.h", "w").write(header)
99
+ ```
100
+
101
+ ## Direct PyTorch ingestion (programmatic, recommended)
102
+
103
+ If you have an in-memory `torch.nn.Sequential` whose modules describe the
104
+ topology, parse it directly — no string declaration required:
105
+
106
+ ```python
107
+ import torch.nn as nn
108
+ from dual_cbf_compiler import parse_pytorch, emit_cpp_header
109
+
110
+ model = nn.Sequential(
111
+ nn.Linear(4, 32), nn.ReLU(),
112
+ nn.Linear(32, 32), nn.ReLU(),
113
+ nn.Linear(32, 1),
114
+ )
115
+ # (load trained weights into model here)
116
+
117
+ network = parse_pytorch(model) # relative_degree=1 by default
118
+ header = emit_cpp_header(network, relative_degree=1)
119
+ open("dual_cbf.h", "w").write(header)
120
+ ```
121
+
122
+ ## PyTorch state_dict from the command line (fallback only)
123
+
124
+ PyTorch state_dicts (`.pt`/`.pth`) only save tensor weights, not the
125
+ computational graph, so the CLI must be told the topology via `--torch-arch`.
126
+ **This is error-prone — a typo silently maps weights to the wrong dimensions.**
127
+ Prefer the ONNX export path above.
128
+
129
+ ```bash
130
+ # Only if ONNX export is unavailable
131
+ dual-cbf-compile model.pt -o dual_cbf.h \
132
+ --torch-arch "4,relu,32,relu,32,linear,1"
133
+ ```
134
+
135
+ ## Use the generated C++ header
136
+
137
+ ```cpp
138
+ #include "dual_cbf.h"
139
+
140
+ float x[4] = {/* state */};
141
+ float f[4] = {/* drift */};
142
+
143
+ // IMPORTANT: G(x) is ROW-MAJOR with shape (n x m).
144
+ // Element G(i, j) lives at G[i * m + j].
145
+ // If you keep G as a 2D C array float G2D[4][2], populate the flat
146
+ // layout as:
147
+ // for (int i = 0; i < 4; ++i)
148
+ // for (int j = 0; j < 2; ++j)
149
+ // G[i * 2 + j] = G2D[i][j];
150
+ float G[4 * 2] = {
151
+ /* row 0 */ 0.0f, 0.0f,
152
+ /* row 1 */ 0.0f, 0.0f,
153
+ /* row 2 */ 0.0f, 0.4f,
154
+ /* row 3 */ 1.0f, 0.0f,
155
+ };
156
+
157
+ float h, Lf, Lg[2];
158
+ dual_cbf::evaluate_cbf(x, f, G, /*m=*/2, &h, &Lf, Lg);
159
+
160
+ // CBF QP constraint: L_f h + L_G h * u >= -alpha(h)
161
+ ```
162
+
163
+ The generated header repeats this row-major layout reminder in its file-level
164
+ comment so the convention is impossible to miss at the call site.
165
+
166
+ ## Relative-degree-2 (hyper-dual)
167
+
168
+ For mechanical systems with acceleration inputs:
169
+
170
+ ```python
171
+ network = parse_onnx("softplus_model.onnx", relative_degree=2)
172
+ header = emit_cpp_header(network, relative_degree=2)
173
+ ```
174
+
175
+ ```cpp
176
+ float L2f, LgLf[m];
177
+ dual_cbf::evaluate_cbf_2nd_order(x, f, G, Df_f, Df_G, m, &L2f, LgLf);
178
+ ```
179
+
180
+ `Df_f` is the user-supplied Jacobian-vector product `f'(x) f(x)` (length `n`),
181
+ and `Df_G` is the row-major Jacobian-vector product `f'(x) G(x)` (shape `n×m`).
182
+
183
+ **ReLU is rejected for relative_degree=2.** ReLU's second derivative vanishes
184
+ almost everywhere, so the Hessian contribution to `L_f^2 h_theta` and
185
+ `L_{col_j(G)} L_f h_theta` would be silently lost. Both `parse_pytorch` and
186
+ `parse_onnx` raise a `ValueError` at parse time if a ReLU layer is detected
187
+ and `relative_degree=2` was requested. Retrain with **Softplus**, **Tanh**,
188
+ or **Sigmoid** instead.
189
+
190
+ ## Verify
191
+
192
+ ```bash
193
+ # Numpy-only verification (no torch needed)
194
+ python3 numpy_verify.py
195
+ python3 numpy_verify_2nd.py
196
+
197
+ # Full suite (requires torch)
198
+ pytest -v dual_cbf_compiler/verify.py
199
+ ```
200
+
201
+ The pytest suite builds random PyTorch networks, evaluates Lie derivatives via
202
+ `torch.autograd`, compiles the generated C++ via `g++`, runs the binary, and
203
+ asserts agreement to single-precision machine epsilon.
204
+
205
+ ## Design
206
+
207
+ * **Zero dynamic allocation.** All weights and biases are embedded as
208
+ `static const float` arrays. A single shared static scratch buffer of
209
+ `2 * max(n_i)` floats (relative-degree 1) or `4 * max(n_i)` floats
210
+ (relative-degree 2) is destructively overwritten as the forward pass
211
+ advances layer by layer.
212
+ * **Forward-only.** The chain rule is collapsed into a memoryless forward
213
+ recurrence by encoding the system state as the real part and a vector
214
+ field as the dual part of an input dual vector. No reverse-mode AD,
215
+ no computational graph.
216
+ * **Algebraic mode selection.** `relative_degree=1` emits standard dual
217
+ algebra (eps^2 = 0). `relative_degree=2` emits hyper-dual arithmetic
218
+ with cross term eps_12, allowing exact extraction of the second-order
219
+ Lie derivatives required for acceleration-controlled mechanical systems.
220
+ * **Hard guards on common footguns.** ReLU + relative_degree=2 is a
221
+ `ValueError`, not a passive warning. The CLI declines to silently map
222
+ weights to the wrong topology — when `--torch-arch` and the state_dict
223
+ disagree, it refuses with a hint to use ONNX.
224
+
225
+ ## Layout
226
+
227
+ ```
228
+ dual_cbf_compiler/
229
+ ir.py — Internal representation (LinearLayer, ActivationLayer)
230
+ parser.py — parse_pytorch, parse_onnx (both accept relative_degree)
231
+ emitter.py — emit_cpp_header
232
+ verify.py — Pytest suite (PyTorch autograd vs g++-compiled binary)
233
+ cli.py — dual-cbf-compile entry point
234
+ setup.py
235
+ ```
@@ -0,0 +1,9 @@
1
+ README.md
2
+ setup.py
3
+ dual_cbf_compiler.egg-info/PKG-INFO
4
+ dual_cbf_compiler.egg-info/SOURCES.txt
5
+ dual_cbf_compiler.egg-info/dependency_links.txt
6
+ dual_cbf_compiler.egg-info/entry_points.txt
7
+ dual_cbf_compiler.egg-info/not-zip-safe
8
+ dual_cbf_compiler.egg-info/requires.txt
9
+ dual_cbf_compiler.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ dual-cbf-compile = dual_cbf_compiler.cli:main
@@ -0,0 +1,19 @@
1
+ numpy>=1.21
2
+
3
+ [dev]
4
+ pytest>=7.0
5
+ torch>=1.13
6
+ onnx>=1.12
7
+ ruff
8
+ mypy
9
+
10
+ [onnx]
11
+ onnx>=1.12
12
+
13
+ [test]
14
+ pytest>=7.0
15
+ torch>=1.13
16
+ onnx>=1.12
17
+
18
+ [torch]
19
+ torch>=1.13
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,60 @@
1
+ """Packaging configuration for dual_cbf_compiler."""
2
+
3
+ from setuptools import find_packages, setup
4
+
5
+ with open("README.md", "r", encoding="utf-8") as fh:
6
+ long_description = fh.read()
7
+
8
+ setup(
9
+ name="dual_cbf_compiler",
10
+ version="0.1.0",
11
+ author="Mohammadreza Kamaldar",
12
+ author_email="mkamaldar@southalabama.edu",
13
+ description=(
14
+ "Ahead-of-time compiler that translates trained neural control barrier "
15
+ "functions into bare-metal C++ headers evaluating exact Lie derivatives "
16
+ "via dual algebra, with zero dynamic memory allocation on embedded targets."
17
+ ),
18
+ long_description=long_description,
19
+ long_description_content_type="text/markdown",
20
+ url="https://github.com/mkamaldar/dual_cbf_compiler",
21
+ license="MIT",
22
+ classifiers=[
23
+ "Development Status :: 4 - Beta",
24
+ "Intended Audience :: Science/Research",
25
+ "License :: OSI Approved :: MIT License",
26
+ "Operating System :: POSIX :: Linux",
27
+ "Operating System :: MacOS",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3.9",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: C++",
34
+ "Topic :: Scientific/Engineering",
35
+ "Topic :: Software Development :: Compilers",
36
+ ],
37
+ keywords=(
38
+ "control-barrier-functions, neural-networks, automatic-differentiation, "
39
+ "embedded-systems, code-generation, dual-numbers, lie-derivatives, "
40
+ "real-time, safety-critical"
41
+ ),
42
+ packages=find_packages(exclude=["tests", "tests.*"]),
43
+ python_requires=">=3.9",
44
+ install_requires=[
45
+ "numpy>=1.21",
46
+ ],
47
+ extras_require={
48
+ "torch": ["torch>=1.13"],
49
+ "onnx": ["onnx>=1.12"],
50
+ "test": ["pytest>=7.0", "torch>=1.13", "onnx>=1.12"],
51
+ "dev": ["pytest>=7.0", "torch>=1.13", "onnx>=1.12", "ruff", "mypy"],
52
+ },
53
+ entry_points={
54
+ "console_scripts": [
55
+ "dual-cbf-compile=dual_cbf_compiler.cli:main",
56
+ ],
57
+ },
58
+ include_package_data=True,
59
+ zip_safe=False,
60
+ )