Code generation¶
OSQP-codegen-style generation of low-level solvers for verified first-order methods, plus a tiny Python wrapper. An LLM coding agent translates each step of the algorithm into the target language and iterates against a Python reference oracle until the generated code is numerically verified.
The code generation guide is the narrative reference for the symbols below, and the tutorials work through five complete examples.
generate_code
¶
generate_code(verifier, next_state=None, out_dir: str | Path = None, config: CodegenConfig | None = None, driver: AgentDriver | None = None, state=None, params=None, name: str = 'fom', code_optimization: bool = False, profile: bool = False, schedules: dict | None = None, iterates=None, param_values: dict | None = None, roll: bool = True) -> CodegenResult
Generate a low-level solver for the FOM recorded in verifier.
Three ways in, selected by what you pass:
iterates=with nonext_stategenerates the whole recorded run, straight from the loop you wrote to verify with. This accepts arbitrary per-iteration coefficients and step types, and anchored methods. It rolls the run back up when repeating one iteration is verified to reproduce it, so a stationary method costs nothing here. Seeextract_unrolled_ir.next_state=generates a rolled solver from one stationary iteration, repeatedconfig.termination.max_iterstimes.- a build function plus
schedules=generates a rolled solver whose declared coefficients are tabulated and read at the loop counter. Seeextract_scheduled_ir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verifier
|
Forwarded to For a method with an iteration-varying coefficient, pass a build
function as |
required | |
next_state
|
Forwarded to For a method with an iteration-varying coefficient, pass a build
function as |
required | |
state
|
Forwarded to For a method with an iteration-varying coefficient, pass a build
function as |
required | |
params
|
Forwarded to For a method with an iteration-varying coefficient, pass a build
function as |
required | |
out_dir
|
str | Path
|
Directory to emit the solver into. |
None
|
config
|
CodegenConfig | None
|
Code-generation configuration. |
None
|
driver
|
AgentDriver | None
|
The coding-agent driver. If |
None
|
name
|
str
|
FOM name used for file naming. |
'fom'
|
code_optimization
|
bool
|
Run the code optimization phase (iterative profile-guided rewriting) after a successful, verified translation. |
False
|
profile
|
bool
|
Collect before/after timing + a profiling breakdown (needs a C compiler). Always skipped silently when no compiler is available. |
False
|
schedules
|
dict | None
|
Iteration-varying scalars, mapping name to a callable of the 0-based
iteration index, a sequence, or a
|
None
|
iterates
|
The successive recorded iterate expressions, or an
Passed without |
None
|
|
param_values
|
dict | None
|
Parameter values, keyed by parameter leaf, used for whichever check the chosen path runs. Optional on the unrolled path, which draws its own. |
None
|
roll
|
bool
|
Unrolled path only: emit the compact rolled IR when repeating one
iteration is verified to reproduce the recording. Pass |
True
|
Source code in fomtools/codegen/generate.py
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
CodegenConfig
¶
Bases: BaseModel
Top-level knobs controlling a code-generation run.
Attributes:
| Name | Type | Description |
|---|---|---|
version |
Version
|
Embedded (no malloc / division-light) or large-scale. |
backend |
Backend
|
Target language. |
termination |
TerminationSpec
|
Loop termination criterion. |
solve_method |
SolveMethod
|
Linear-system solution strategy. |
dtype |
{'float64', 'float32'}
|
Floating-point type emitted in the C ABI ( |
tol_verify |
float or None
|
Tolerance used by the equivalence harness when comparing generated-code output against the Python reference oracle. When left unset it defaults by dtype (1e-6 for float64, 1e-4 for float32, since single precision cannot meet a 1e-6 gate); set it explicitly to override. |
tol_kernel |
float or None
|
Tolerance of the direct checks of each |
num_verify_samples |
int
|
Number of random parameter instances drawn for the golden verify data. |
seed |
int
|
RNG seed for reproducible verify-sample generation. |
agent_timeout_s |
int
|
Wall-clock budget, in seconds, for the translation phase, shared by all of its agent attempts. Default 600. |
agent_optimize_max_turns |
int
|
Turn budget for one coding-agent attempt at the code optimization phase. Default 200. |
agent_optimize_timeout_s |
int
|
Wall-clock budget, in seconds, for one round of the code optimization phase. Default 7200. |
agent_optimize_rounds |
int
|
Maximum number of code optimization rounds. Default 5. |
agent_optimize_min_gain |
float
|
A round that makes the solver less than this much faster (relative) ends the phase. Default 0.02. |
cg_auto_min_dim |
int
|
Dimension threshold for the |
Source code in fomtools/codegen/config.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |
TerminationSpec
¶
Bases: BaseModel
Termination criterion for the generated solve loop.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
TerminationKind
|
Fixed iteration count, infinity-norm change, or the verification objective, each with early exit except the first. |
max_iters |
int
|
Hard upper bound on iterations. Always required: embedded targets size their (static) iteration accounting from it and every loop needs a guard. |
tol |
float or None
|
Tolerance for the |
check_termination |
int
|
How often the criterion is evaluated (the name and semantics follow
OSQP's setting): For For |
Source code in fomtools/codegen/config.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
uses_objective
property
¶
uses_objective: bool
Whether the loop evaluates the verification objective (FOM_USE_OBJECTIVE).
True even with check_termination == 0: the objective is then still
evaluated, and tested, once at the last iteration.
uses_tolerance
property
¶
uses_tolerance: bool
Whether the loop checks the infinity-norm change criterion at all.
Single source of truth shared by the emitted header (FOM_USE_TOL)
and the reference oracle, so the generated code and the verification
ground truth can never disagree on when early exit is possible.
is_check_iteration
¶
is_check_iteration(k: int, max_iter: int | None = None) -> bool
Whether the 1-based iteration k evaluates the OBJECTIVE criterion.
Every check_termination-th iteration, and the last one (max_iter,
defaulting to max_iters). Shared by the oracle and the emitted
verify data so both test at the same iterations.
Source code in fomtools/codegen/config.py
194 195 196 197 198 199 200 201 202 203 | |
TerminationKind
¶
Bases: str, Enum
How the generated solve loop decides to stop.
MAX_ITERS runs a fixed iteration count (exactly matches the verifier /
simulator semantics, so it is the most robust to verify). INF_NORM_CHANGE
additionally stops early once ||x_k - x_{k-1}||_inf <= tol.
OBJECTIVE stops early once the verification objective r^k -- the
performance metric set with Verifier.maximize,
e.g. a fixed-point or KKT residual, in the norm it was set with -- is at most
tol. The stopping test is then exactly the certified quantity: if
verification shows r^K <= tol over the whole parameter set, the generated
solver stops within K iterations. The norm follows the verifier's
convention, so ord=2 is the squared two-norm and tol bounds it.
Source code in fomtools/codegen/config.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | |
extract_unrolled_ir
¶
extract_unrolled_ir(verifier, iterates, config: CodegenConfig | None = None, name: str = 'fom', state=None, params=None, dedup: bool = True, check: bool = True, roll: bool = True, param_values: dict | None = None) -> FomIR
Extract the whole recorded run as one unrolled body.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verifier
|
The |
required | |
iterates
|
The iterate sequence, either an
|
required | |
config
|
CodegenConfig | None
|
Code-generation configuration. Its termination is replaced by the
recorded horizon (a single pass when unrolled). |
None
|
state
|
Optional explicit leaf lists, as for
|
None
|
|
params
|
Optional explicit leaf lists, as for
|
None
|
|
dedup
|
bool
|
Merge coefficient blocks holding identical numbers. |
True
|
check
|
bool
|
Verify the unrolled result against the recorded tape before returning.
Does not apply to a rolled result: there the check is what decides to roll
in the first place, so it cannot be skipped without changing the answer.
Combine with |
True
|
roll
|
bool
|
Emit the compact rolled IR when repeating one iteration is verified to
reproduce the recording. Pass |
True
|
param_values
|
dict | None
|
Parameter values for the checks, keyed by parameter leaf. Defaults to deterministic draws inside the declared box. Supplying them adds a draw to the roll decision rather than replacing the default ones: no single draw, the caller's included, is enough to license a roll. |
None
|
Returns:
| Type | Description |
|---|---|
FomIR
|
Either a rolled IR ( |
Source code in fomtools/codegen/extract_unrolled.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
extract_ir
¶
extract_ir(verifier, next_state, state=None, params=None, config: CodegenConfig | None = None, name: str = 'fom', iterates=None) -> FomIR
Build a FomIR for one iteration of the FOM recorded in verifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verifier
|
A |
required | |
next_state
|
The iterate |
required | |
state
|
Optional explicit list of initial-state leaves. When |
None
|
|
params
|
Optional explicit list of parameter leaves. When |
None
|
|
config
|
CodegenConfig | None
|
Code-generation configuration (supplies the termination spec / dtype). |
None
|
name
|
str
|
Human-friendly FOM name used for file naming. |
'fom'
|
iterates
|
Optional recorded iterate sequence. Used only under
|
None
|
Returns:
| Type | Description |
|---|---|
FomIR
|
The single-iteration intermediate representation. |
Raises:
| Type | Description |
|---|---|
ObjectiveExtractionError
|
Under |
Source code in fomtools/codegen/extract.py
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
extract_scheduled_ir
¶
extract_scheduled_ir(build: Callable[..., Recording], schedules: dict, config: CodegenConfig | None = None, name: str = 'fom') -> FomIR
Extract an IR whose coefficients vary with the iteration index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
build
|
Callable[..., Recording]
|
A function that records one iteration and returns a
|
required |
schedules
|
dict
|
Maps a schedule name to a callable of the 0-based iteration index, a
sequence of values, or a |
required |
config
|
CodegenConfig | None
|
Code-generation configuration; its |
None
|
name
|
str
|
Human-friendly FOM name used for file naming. |
'fom'
|
Returns:
| Type | Description |
|---|---|
FomIR
|
A single-iteration IR carrying the schedule tables and scaled terms. |
Raises:
| Type | Description |
|---|---|
NonStationaryFOMError
|
If the recording changes shape between probes. |
ScheduleFitError
|
If a coefficient's dependence on the schedule is not affine, or the varying quantity reaches somewhere a table cannot (a factorized system matrix, an activation scalar, a constant offset). |
Source code in fomtools/codegen/extract_scheduled.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
FomIR
dataclass
¶
Complete IR for one repeatable iteration, or for a whole unrolled run.
Attributes:
| Name | Type | Description |
|---|---|---|
params |
tuple[ParamSpec, ...]
|
Solve-time parameter vectors. |
state |
StateSpec
|
Loop-carried state layout + initial value. For an unrolled IR this is the solver's input: the initial iterates, plus any earlier iterate the method keeps referring to (a Halpern anchor, say). |
body |
tuple[IterationStep, ...]
|
Ordered iteration-body steps producing temporaries. For an unrolled IR this is the whole run as one straight-line program, in dependency order. |
state_update |
LinearOp
|
Linear op producing the next state from current state + temporaries. For an unrolled IR it produces the final answer. |
termination |
TerminationSpec
|
Loop termination criterion. |
matrices |
dict[str, MatrixData]
|
All named coefficient/const blocks referenced by the ops. |
schedules |
dict[str, ndarray]
|
Iteration-varying scalars referenced by |
dtype |
str
|
Numeric dtype string ( |
name |
str
|
Human-friendly FOM name (used for fixtures / file naming). |
unrolled |
bool
|
Whether |
objective |
ObjectiveSpec | None
|
The verification objective the loop stops on under
|
Source code in fomtools/codegen/ir.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |
max_rhs_dim
property
¶
max_rhs_dim: int
Largest intermediate vector size; used to statically size scratch.
linops
¶
linops() -> list[LinearOp]
Every linear op: the body steps', the state update, and the objective's.
Source code in fomtools/codegen/ir.py
489 490 491 492 493 494 | |
objective_inputs
¶
objective_inputs() -> list[str]
The parameter and temporary sources the objective reads, in the order
fom_objective takes them after (it, state, new_state): parameters in
declaration order, then temporaries in body order.
Source code in fomtools/codegen/ir.py
478 479 480 481 482 483 484 485 486 487 | |
tmp_dims
¶
tmp_dims() -> dict[str, int]
Map each temporary name to its dimension.
Source code in fomtools/codegen/ir.py
474 475 476 | |
extract_objective
¶
extract_objective(verifier, state_layout, next_state_exprs, param_map, tmp_map, matrices: dict, iterates=None) -> ObjectiveSpec
Map the objective set on verifier onto the loop extracted by
extract_ir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verifier
|
The recording, with its objective set. |
required | |
state_layout
|
|
required | |
next_state_exprs
|
|
required | |
param_map
|
|
required | |
tmp_map
|
|
required | |
matrices
|
dict
|
The IR's matrix table; the objective's coefficient blocks are added to it. |
required |
iterates
|
The recorded iterate sequence (one entry per iteration, normalized), if any. Enables the last-recorded-iteration frame. |
None
|
Raises:
| Type | Description |
|---|---|
ObjectiveExtractionError
|
If no objective is set, or it reads something the loop does not carry. |
Source code in fomtools/codegen/objective.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | |
ObjectiveExtractionError
¶
Bases: ValueError
The verification objective cannot be evaluated by the generated loop.
Source code in fomtools/codegen/objective.py
70 71 | |
ReferenceOracle
¶
Rolled NumPy executor of a FomIR.
Source code in fomtools/codegen/oracle.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
objective_value
¶
objective_value(sources: dict[str, ndarray], it: int) -> float
The verification objective r^k at the end of 0-based iteration it.
sources must hold state (w^{k-1}), new_state (w^k), the
parameters and that iteration's temporaries.
Source code in fomtools/codegen/oracle.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
solve
¶
solve(param_values: dict[str, ndarray] | None = None, x0: ndarray | None = None) -> OracleResult
Run the rolled loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param_values
|
dict[str, ndarray] | None
|
Mapping from parameter name ( |
None
|
x0
|
ndarray | None
|
Optional initial state; defaults to the IR's stored init. |
None
|
Source code in fomtools/codegen/oracle.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
AgentDriver
¶
Bases: ABC
Abstract coding-agent that generates a source file until verify passes.
Subclasses implement run to drive a particular backend (the real
Claude/Codex/Pi CLIs, or StubAgentDriver
for tests). The driver owns only task.solver_rel_path; all other files
are restored via task.restore_hook before each verify.
Methods:
| Name | Description |
|---|---|
run |
Produce/refine the solver source until the verify command passes. |
Source code in fomtools/codegen/agent/driver.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
run
abstractmethod
¶
run(task: AgentTask) -> AgentResult
Produce/refine task.solver_rel_path until task.verify_cmd passes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
AgentTask
|
The unit of work describing the workspace, the solver path to write, the restore hook, and the verify command to run. |
required |
Returns:
| Type | Description |
|---|---|
AgentResult
|
The outcome, whose |
Source code in fomtools/codegen/agent/driver.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
StubAgentDriver
¶
Bases: AgentDriver
A deterministic AgentDriver that writes a fixed solver source.
Instead of calling an LLM, it writes a pre-supplied ("golden") solver body into the workspace and runs the real verify command, letting the full code-generation pipeline be exercised in CI without a model or network.
Methods:
| Name | Description |
|---|---|
run |
Write the fixed source into the task workspace and verify it. |
Source code in fomtools/codegen/agent/stub.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
__init__
¶
__init__(solver_source: str | Path, extra_sources: dict[str, str | Callable[[str], str]] | None = None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solver_source
|
str or Path
|
The golden solver body. Either C source text, or a path ( |
required |
extra_sources
|
dict
|
Other files to write on every run, keyed by path relative to the workspace: either the text to write, or a callable that maps the file's current text to the new one (e.g. to rewrite the generated linear solve). Lets tests exercise edits the pipeline must keep or revert. |
None
|
Source code in fomtools/codegen/agent/stub.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
run
¶
run(task: AgentTask) -> AgentResult
Write the fixed source into the workspace and run the verify command.
Implements the AgentDriver interface. The stored source is
written to task.solver_rel_path, task.restore_hook is invoked (if present) to
restore the deterministic files before verifying; then task.verify_cmd is run in
task.workdir and its exit code decides success.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
AgentTask
|
The unit of work describing the workspace, the solver path to write, the restore hook, and the verify command to run. |
required |
Returns:
| Type | Description |
|---|---|
AgentResult
|
The outcome, whose |
Source code in fomtools/codegen/agent/stub.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |