XVII · Python C-ABI (welvet on PyPI) / CHAPTER 28
Python C-ABI: train SGD and .entity round-trip
welvet (PyPI)cpu_tiled
Why it exists
Training and checkpoints should match the Go ENTITY path so Python scripts can hand off to Go apps (and back).
What it is
Train one Dense step with train_sgd, serialize to .entity bytes, deserialize a second grid, and free both handles.
Checkpoint bytes
serialize_entity returns the same Welvet .entity blob the Go engine writes. deserialize_entity returns a new grid handle: always free_grid both. For cameral / named train modes see Go book §67 and Python list_named_train_modes() / train_stack_mse.
Requirements: chapter 114.
Python example
examples/116-python-train-entity/main.py
Run:
cd welvet/examples/116-python-train-entity && python3 main.py"""116. Python C-ABI: train SGD and .entity round-trip."""
from __future__ import annotations
import welvet as w
def main() -> None:
w.assert_engine_version()
g = w.create_grid(backend="cpu_tiled")
try:
w.place_dense(
g,
{"in": 8, "out": 4, "act": "relu", "dtype": w.DType.FLOAT32},
)
x = [0.05 * (i + 1) for i in range(8)]
y = [0.0, 0.0, 0.0, 1.0]
result = w.train_sgd(g, x, y, lr=0.05)
print("train", result)
blob = w.serialize_entity(g)
print("entity_bytes", len(blob))
finally:
w.free_grid(g)
g2 = w.deserialize_entity(blob)
try:
out = w.forward(g2, x)
print("reloaded_out", [round(v, 4) for v in out])
finally:
w.free_grid(g2)
if __name__ == "__main__":
main()
Output
train {'loss': 0.25, 'status': 'ok'}
entity_bytes 550
reloaded_out [0.0, 0.0, 0.0, 0.0127]
Validate (harness)
cd welvet/examples/116-python-train-entity && PYTHONPATH=../../../w2a/python/src python3 main.py