Build and Validate a Graph

Learn to diagnose a declared dtype mismatch, confirm a corrected graph, and submit values for execution. You should already know basic Python and what NumPy arrays and PyTorch tensors are; no training expertise is needed. The tiny model only gives us a concrete payload to pass between steps.

Run it

Follow tutorial setup, then run from the repository root:

python -m tutorials.build_graph

Open tutorials/01_build_graph.ipynb for the guided lesson. The Python snippets below are consecutive notebook cells: run them in Jupyter with top-level await. For a terminal run, use the module command above.

1. Follow the two flows

The dataset flows through PrepareDataset → TrainModel. A model flows through TrainModel → ScaleModel. TrainModel waits for both inputs. An Artifact names a data position; its value belongs to a submission. An operator that outputs the same artifact replaces that value along its flow.

The builder declares both entry flows because the application supplies both the initial table and the initial model. Inspect it before executing anything.

import asyncio
import inspect
import numpy as np
import torch
from jayrun import ArtifactContext, Engine, Submission
from jayrun.context import ContextState
from tutorials import build_graph as lesson

print(inspect.getsource(lesson.build_graph))

2. Diagnose a declaration without running it

PrepareDataset promises the dtype selected by the builder. TrainModel requires float32. Choose float64 and inspect the report: exactly one producer/consumer edge should be incompatible. Validation compares declared properties; it does not examine actual input arrays.

bad, _, _ = lesson.build_graph(torch.float64)
validation = bad.validate()
print("Valid:", validation.valid)
print("Mismatched edges:", len(validation.mismatched_edges))
assert not validation.valid and len(validation.mismatched_edges) == 1

graph, dataset, model = lesson.build_graph(torch.float32)
assert graph.validate().valid
graph.confirm()
print("Corrected graph confirmed:", graph.confirmed)

3. Supply values and inspect the outcome

The table has 784 feature columns and one label column. ArtifactContext maps the two entry identities to a table and a classifier. Constructors declare fields; Jayrun binds artifact arguments to fields by name and output tuples by position. Build a Submission before opening the Engine. Inspect the two entry IDs without reading the table or classifier. Each call to arguments() supplies fresh builders for a run and shares the original payloads.

Jupyter owns an event loop, so the synchronous Engine block runs through asyncio.to_thread. This is orchestration code using the existing tutorial operators.

def execute_corrected_graph(candidate, exit_artifact):
    rng = np.random.default_rng(42)
    table = np.column_stack((rng.normal(size=(24, 784)), np.arange(24) % 10))
    with torch.random.fork_rng(devices=[]):
        torch.manual_seed(42)
        classifier = torch.nn.Linear(784, 10)
    inputs = ArtifactContext({dataset: table, model: classifier})
    submission = Submission(candidate, artifacts=inputs)
    entries = submission.inspect()["entries"]
    assert len(entries) == 2 and all(entry["supplied"] for entry in entries)
    with Engine() as engine:
        run = engine.submit(**submission.arguments())
        run.wait(timeout=30)
        if run.state is not ContextState.FINISHED:
            raise RuntimeError(str(run.report.data.failure))
        return run.artifact(exit_artifact).value

result = await asyncio.to_thread(execute_corrected_graph, graph, model)
print("Result type:", type(result).__name__)
assert isinstance(result, lesson.TemperatureScaledModel)

4. Try another declaration

Predict what happens if the producer declares float16. Run the cell to check your prediction. Then change float16 to float32: the mismatch count should become zero. A fixed declaration still does not prove model quality or runtime payload correctness.

alternative, _, _ = lesson.build_graph(torch.float16)
print("Alternative mismatches:", len(alternative.validate().mismatched_edges))

5. Attach an independent measurement

A model auditor wants the number of trained parameters. Declare that measurement against a separate artifact, then append its flow to the trained model. The extended run exposes the count as its exit. The confirmed training graph still exposes the trained model.

class CountParameters(BaseOperator):
    """Count trainable and frozen parameters in a trained model."""

    requirements = ("torch",)

    def __init__(self, *, trained: Artifact, outputs: tuple[Artifact | None, ...]) -> None:
        super().__init__()
        self.trained = ArtifactField(properties=(TypeProperty(torch.nn.Module),))
        self.outputs = (ArtifactField(properties=(TypeProperty(int),)),)

    def execute(self) -> int:
        return sum(parameter.numel() for parameter in self.trained.value.parameters())
from jayrun import Artifact, ArtifactFlow

trained, count = Artifact(name="trained"), Artifact(name="parameter count")
measurement = ArtifactFlow(lesson.CountParameters(trained=trained, outputs=(count,)), artifact=trained)
extended = graph.attach(measurement, model, position="end")
assert len(graph.flow(model).operators) == 2
assert len(extended.flow(model).operators) == 3
extended.confirm()

total = await asyncio.to_thread(execute_corrected_graph, extended, count)
assert total == 7_850  # 784 weights and one bias for each of ten classes
print(total)

You have separated declaration, validation, confirmation, submission, and result inspection. The complete CLI demonstration also returns mismatches_detected=1, corrected_valid=True, and result_type=”TemperatureScaledModel”. Continue to the image lesson for conditional routes and reusable resources.

Read the canonical implementation

The complete build_graph.py supplies the operators and application helpers used above. This excerpt shows graph wiring:

def build_graph(dtype: torch.dtype = torch.float32):
    dataset = Artifact(name="dataset")
    model = Artifact(name="model")

    prepare = PrepareDataset(
        dataset=dataset,
        dtype=dtype,
        outputs=(dataset,),
        name="prepare_dataset",
    )
    train = TrainModel(
        dataset=dataset,
        model=model,
        outputs=(model,),
        name="train_model",
    )
    scale = ScaleModel(
        model=model,
        outputs=(model,),
        name="scale_model",
    )

    dataset_flow = ArtifactFlow(
        prepare,
        train,
        artifact=dataset,
    )
    model_flow = ArtifactFlow(
        train,
        scale,
        artifact=model,
    )

    graph = GraphDefinition(
        dataset_flow,
        model_flow,
        entry_flows=(dataset_flow, model_flow),
    )
    return graph, dataset, model

Continue with the tutorial collection or supported behavior and limitations.

Extend a graph built by another author

The two-channel sensor example starts with a confirmed graph and adds two input calibration rows and two measurement rows. Run python docs/_examples/attach_flows.py with Jayrun installed. The final score is 42.0. Each multi-input operator executes once. The original graph can still accept the two calibrated inputs directly. The construction guide also shows insertion before and after an existing reader.