.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples_runtime/plot_pipeline_proto.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_runtime_plot_pipeline_proto.py: .. _l-example-pipeline-proto: Builds, saves, and runs a small generation pipeline =================================================== ``PipelineProto`` bundles models, tensor-interface names, and generation settings. This example creates all weights locally, validates the container, saves and reloads its binary representation, and generates tokens from the reloaded models. No tokenizer, external model, or download is needed: the vocabulary is simply the integers 0, 1, and 2. The Python runtime currently accepts individual models, not ``PipelineProto`` itself. A binding for the C++ ``Generate(PipelineProto, ...)`` overload is still needed for direct container execution. Below, we explicitly pass the restored models and supported settings to ``ReferenceEvaluator.generate`` instead. Serialization alone does not execute a pipeline. .. GENERATED FROM PYTHON SOURCE LINES 19-31 .. code-block:: Python from pathlib import Path from tempfile import TemporaryDirectory import numpy from onnx_light import onnx import onnx_light.onnx.helper as oh import onnx_light.onnx.numpy_helper as onh from onnx_light.onnx.reference import ReferenceEvaluator from onnx_light.onnx_proto import verify .. GENERATED FROM PYTHON SOURCE LINES 32-45 Create two tiny stages ---------------------- ``prefill`` is required. ``embedding`` optionally maps token IDs to features; ``decode`` optionally stores a separate model for subsequent tokens and state. The current generation runtime does not support a separate decode model, so this example omits it and uses prefill for both the prompt and later steps. Without persistent cache bindings, each step evaluates the full growing prefix. The embedding table makes greedy decoding follow 0 -> 1 -> 2 -> 0. Its output and the prefill input are both named ``inputs_embeds``: stages exchange values by matching names, not by a connection or renaming graph. Private initializer/intermediate names must be unique across stages. .. GENERATED FROM PYTHON SOURCE LINES 45-73 .. code-block:: Python embedding = oh.make_model( oh.make_graph( [oh.make_node("Gather", ["transition_table", "input_ids"], ["inputs_embeds"])], "embedding", [oh.make_tensor_value_info("input_ids", onnx.TensorProto.INT64, ["B", "S"])], [oh.make_tensor_value_info("inputs_embeds", onnx.TensorProto.FLOAT, ["B", "S", 3])], initializer=[ onh.from_array( numpy.array([[0, 4, 0], [0, 0, 4], [4, 0, 0]], dtype=numpy.float32), name="transition_table", ) ], ), opset_imports=[oh.make_opsetid("", 23)], ir_version=10, ) prefill = oh.make_model( oh.make_graph( [oh.make_node("Identity", ["inputs_embeds"], ["logits"])], "prefill", [oh.make_tensor_value_info("inputs_embeds", onnx.TensorProto.FLOAT, ["B", "S", 3])], [oh.make_tensor_value_info("logits", onnx.TensorProto.FLOAT, ["B", "S", 3])], ), opset_imports=[oh.make_opsetid("", 23)], ir_version=10, ) .. GENERATED FROM PYTHON SOURCE LINES 74-90 Set generation parameters and interface names --------------------------------------------- Zero temperature selects deterministic greedy decoding. The seed would control sampling at positive temperatures. EOS ends generation early; padding applies to already-finished rows in a batch. At positive temperature, logits are scaled first, then top-k retains at most k tokens, then top-p keeps the smallest prefix reaching p of the remaining, renormalized probability mass. Ties favor lower token IDs. Zero k disables top-k; k above the vocabulary retains all tokens. Unset top-p or top-p=1 disables nucleus filtering; otherwise p must be in (0, 1]. Greedy decoding ignores valid filters, but invalid settings are still rejected. ReferenceEvaluator.generate uses the standard interface names shown here. The optional mask and position names do not add inputs to these tiny graphs. verify_pipeline checks model structure and parameter ranges, not whether a particular execution API supports every stored setting. .. GENERATED FROM PYTHON SOURCE LINES 90-112 .. code-block:: Python pipeline = onnx.PipelineProto( name="three_token_cycle", embedding=embedding, prefill=prefill, max_new_tokens=4, temperature=0.0, seed=42, eos_token_ids=[2], pad_token_id=0, top_k=0, input_ids_name="input_ids", logits_name="logits", attention_mask_name="attention_mask", position_ids_name="position_ids", ) verify.verify_pipeline(pipeline) assert pipeline.HasField("prefill") assert pipeline.HasField("embedding") assert not pipeline.HasField("decode") assert not pipeline.HasField("top_p") .. GENERATED FROM PYTHON SOURCE LINES 113-119 Save and reload the binary container ------------------------------------- The .pipeline and .pipe-onnx extensions select PipelineProto when loading. A temporary directory keeps the example from leaving files behind, including when Sphinx Gallery executes it. .. GENERATED FROM PYTHON SOURCE LINES 119-151 .. code-block:: Python with TemporaryDirectory() as directory: path = Path(directory) / "cycle.pipeline" onnx.save(pipeline, path) restored = onnx.load(path) verify.verify_pipeline(restored) assert not restored.HasField("top_p") for stage in ("embedding", "prefill", "decode"): assert restored.HasField(stage) == pipeline.HasField(stage) if pipeline.HasField(stage): assert ( getattr(restored, stage).SerializeToString() == getattr(pipeline, stage).SerializeToString() ) for setting in ( "name", "max_new_tokens", "temperature", "seed", "pad_token_id", "top_k", "input_ids_name", "logits_name", "attention_mask_name", "position_ids_name", ): assert restored.HasField(setting) assert getattr(restored, setting) == getattr(pipeline, setting) assert list(restored.eos_token_ids) == [2] print("Binary round trip preserved stages, settings, and interface names.") .. rst-class:: sphx-glr-script-out .. code-block:: none Binary round trip preserved stages, settings, and interface names. .. GENERATED FROM PYTHON SOURCE LINES 152-159 Generate from the restored models ----------------------------------- ReferenceEvaluator imports the native runtime, which registers its kernels unconditionally. The supported split-model Python API runs embedding before prefill on every step. It does not automatically read PipelineProto settings: forward them explicitly, using the standard tensor names configured above. .. GENERATED FROM PYTHON SOURCE LINES 159-179 .. code-block:: Python embedding_evaluator = ReferenceEvaluator(restored.embedding) evaluator = ReferenceEvaluator(restored.prefill) feeds = {restored.input_ids_name: numpy.array([[0]], dtype=numpy.int64)} tokens = evaluator.generate( feeds, embedding=embedding_evaluator, max_new_tokens=restored.max_new_tokens, temperature=restored.temperature, top_k=restored.top_k, top_p=restored.top_p if restored.HasField("top_p") else None, seed=restored.seed, eos_token_ids=list(restored.eos_token_ids), pad_token_id=restored.pad_token_id, ) numpy.testing.assert_array_equal(tokens, [[0, 1, 2]]) assert tokens.dtype == numpy.int64 numpy.testing.assert_array_equal(feeds["input_ids"], [[0]]) print("Tokens (including prompt, stopping at EOS):", tokens.tolist()) .. rst-class:: sphx-glr-script-out .. code-block:: none Tokens (including prompt, stopping at EOS): [[0, 1, 2]] .. GENERATED FROM PYTHON SOURCE LINES 180-184 Disable EOS to observe the token limit -------------------------------------- This is an explicit execution-time override; the saved pipeline is unchanged. .. GENERATED FROM PYTHON SOURCE LINES 184-195 .. code-block:: Python limited = evaluator.generate( feeds, embedding=embedding_evaluator, max_new_tokens=restored.max_new_tokens, temperature=restored.temperature, seed=restored.seed, ) numpy.testing.assert_array_equal(limited, [[0, 1, 2, 0, 1]]) assert list(restored.eos_token_ids) == [2] print("Tokens (including prompt, stopping at token limit):", limited.tolist()) .. rst-class:: sphx-glr-script-out .. code-block:: none Tokens (including prompt, stopping at token limit): [[0, 1, 2, 0, 1]] .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.005 seconds) .. _sphx_glr_download_auto_examples_runtime_plot_pipeline_proto.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_pipeline_proto.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_pipeline_proto.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_pipeline_proto.zip ` .. include:: plot_pipeline_proto.recommendations .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_