Skip to content

Commit cd5793b

Browse files
doc: Python API for PyTorch example (#24)
#### Relevant issue or PR Closes #6. #### Description of changes Context manager for `pytorch_optimization` example. #### Testing done CI + manual. #### License - [x] By submitting this pull request, I confirm that my contribution is made under the terms of the [Apache 2.0 license](https://pasteurlabs.github.io/tesseract/LICENSE). - [x] I sign the Developer Certificate of Origin below by adding my name and email address to the `Signed-off-by` line. <details> <summary><b>Developer Certificate of Origin</b></summary> ```text Developer Certificate of Origin Version 1.1 Copyright (C) 2004, 2006 The Linux Foundation and its contributors. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` </details> Signed-off-by: Matteo Salvador <matteo.salvador@simulation.science> --------- Signed-off-by: Niklas Heim <niklas.heim@simulation.science> Co-authored-by: Niklas Heim <niklas.heim@simulation.science>
1 parent 1379d91 commit cd5793b

File tree

2 files changed

+45
-76
lines changed

2 files changed

+45
-76
lines changed

examples/sciml/pytorch_optimization/optimization.py

Lines changed: 45 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
# Copyright 2025 Pasteur Labs. All Rights Reserved.
22
# SPDX-License-Identifier: Apache-2.0
33

4+
45
import argparse
56

67
import matplotlib.pyplot as plt
78
import numpy as np
89
import torch
9-
from tesseract_api import log_rosenbrock
10-
from tesseract_client import Client
10+
11+
# disabling jit compiler for now
12+
import torch._dynamo
13+
14+
torch._dynamo.config.disable = True
15+
16+
from tesseract_api import log_rosenbrock # noqa: E402
17+
18+
from tesseract_core import Tesseract # noqa: E402
1119

1220
parser = argparse.ArgumentParser()
13-
parser.add_argument("-p", "--port", help="Port of tesseract server", required=True)
1421
parser.add_argument("-n", "--niter", help="The number of iterations", default=300)
1522
parser.add_argument(
1623
"-l",
@@ -31,8 +38,6 @@
3138

3239
args = vars(parser.parse_args())
3340

34-
port = int(args["port"])
35-
3641
torch.manual_seed(int(args["seed"]))
3742

3843
# initiate starting x, y
@@ -53,9 +58,6 @@
5358
"b": b,
5459
}
5560

56-
# Initialize Tesseract client
57-
client = Client(host="127.0.0.1", port=port)
58-
5961
# setup optimizer: either Adam or SGD (default)
6062
assert args["opt"] in ["SGD", "Adam"], "Only Adam or SGD optimizer supported."
6163
opt = getattr(torch.optim, args["opt"])((x0, y0), lr=float(args["lr"]))
@@ -64,46 +66,41 @@
6466
losses = []
6567
x = []
6668
y = []
67-
for _i in range(int(args["niter"])):
68-
# zero out the gradients
69-
opt.zero_grad()
70-
71-
# get loss
72-
output = client.request("apply", method="POST", payload={"inputs": inputs})
73-
loss = output["loss"]["data"]["buffer"]
74-
75-
# append values
76-
losses.append(loss)
77-
x.append(inputs["x"])
78-
y.append(inputs["y"])
79-
80-
# get gradients
81-
jacobian_response = client.request(
82-
"jacobian",
83-
method="POST",
84-
payload={
85-
"inputs": inputs,
86-
"jac_inputs": jac_inputs,
87-
"jac_outputs": ["loss"],
88-
},
89-
)
90-
91-
# insert gradients into pytorch tensors where optimizer expects them
92-
if "x" in jac_inputs:
93-
x0.grad = torch.as_tensor(
94-
jacobian_response["loss"]["x"]["data"]["buffer"]
95-
).unsqueeze(0)
96-
if "y" in jac_inputs:
97-
y0.grad = torch.as_tensor(
98-
jacobian_response["loss"]["y"]["data"]["buffer"]
99-
).unsqueeze(0)
100-
101-
# make optimization step
102-
opt.step()
103-
104-
# update inputs
105-
inputs["x"] = x0.detach().item()
106-
inputs["y"] = y0.detach().item()
69+
with Tesseract.from_image(image="pytorch_optimization") as pytorch_optimization:
70+
for _i in range(int(args["niter"])):
71+
# zero out the gradients
72+
opt.zero_grad()
73+
74+
# get loss
75+
output = pytorch_optimization.apply(inputs)
76+
loss = output["loss"]
77+
78+
# append values
79+
losses.append(loss)
80+
x.append(inputs["x"])
81+
y.append(inputs["y"])
82+
83+
# get gradients
84+
jacobian_response = pytorch_optimization.jacobian(
85+
inputs=inputs, jac_inputs=jac_inputs, jac_outputs=["loss"]
86+
)
87+
88+
# insert gradients into pytorch tensors where optimizer expects them
89+
if "x" in jac_inputs:
90+
x0.grad = (
91+
torch.as_tensor(jacobian_response["loss"]["x"]).float().unsqueeze(0)
92+
)
93+
if "y" in jac_inputs:
94+
y0.grad = (
95+
torch.as_tensor(jacobian_response["loss"]["y"]).float().unsqueeze(0)
96+
)
97+
98+
# make optimization step
99+
opt.step()
100+
101+
# update inputs
102+
inputs["x"] = x0.detach().item()
103+
inputs["y"] = y0.detach().item()
107104

108105
# plotting
109106
X, Y = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100), indexing="xy")

examples/sciml/pytorch_optimization/tesseract_client.py

Lines changed: 0 additions & 28 deletions
This file was deleted.

0 commit comments

Comments
 (0)