.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/plot_create_model_random_weights.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_plot_create_model_random_weights.py: Convert a random-weight model with ``create_model`` =================================================== This example shows the core workflow of mbext on a **tiny, randomly initialised** model. Nothing is downloaded from the Hugging Face hub: a small :class:`~transformers.LlamaConfig` is built with a single hidden layer and random weights, converted to ONNX with :func:`modelbuilder.builder.create_model`, and the ONNX logits are compared to the PyTorch reference. This is exactly how the fast test suite validates every architecture, which is why the tests run offline and in seconds (see the *Design* page). .. GENERATED FROM PYTHON SOURCE LINES 19-25 .. code-block:: Python import os import tempfile import numpy as np .. GENERATED FROM PYTHON SOURCE LINES 26-30 Build a tiny random-weight model -------------------------------- A minimal ``LlamaForCausalLM`` with small dimensions and a single hidden layer. The weights are randomly initialised (seeded for reproducibility). .. GENERATED FROM PYTHON SOURCE LINES 30-54 .. code-block:: Python import torch from tokenizers import Tokenizer from tokenizers.models import WordLevel from transformers import AutoModelForCausalLM, LlamaConfig, PreTrainedTokenizerFast num_hidden_layers = 1 config = LlamaConfig( architectures=["LlamaForCausalLM"], hidden_size=512, intermediate_size=1376, max_position_embeddings=2048, num_attention_heads=8, num_key_value_heads=4, num_hidden_layers=num_hidden_layers, vocab_size=1024, bos_token_id=1, eos_token_id=2, ) head_size = config.hidden_size // config.num_attention_heads torch.manual_seed(42) model = AutoModelForCausalLM.from_config(config) model.eval() .. rst-class:: sphx-glr-script-out .. code-block:: none LlamaForCausalLM( (model): LlamaModel( (embed_tokens): Embedding(1024, 512) (layers): ModuleList( (0): LlamaDecoderLayer( (self_attn): LlamaAttention( (q_proj): Linear(in_features=512, out_features=512, bias=False) (k_proj): Linear(in_features=512, out_features=256, bias=False) (v_proj): Linear(in_features=512, out_features=256, bias=False) (o_proj): Linear(in_features=512, out_features=512, bias=False) ) (mlp): LlamaMLP( (gate_proj): Linear(in_features=512, out_features=1376, bias=False) (up_proj): Linear(in_features=512, out_features=1376, bias=False) (down_proj): Linear(in_features=1376, out_features=512, bias=False) (act_fn): SiLUActivation() ) (input_layernorm): LlamaRMSNorm((512,), eps=1e-06) (post_attention_layernorm): LlamaRMSNorm((512,), eps=1e-06) ) ) (norm): LlamaRMSNorm((512,), eps=1e-06) (rotary_emb): LlamaRotaryEmbedding() ) (lm_head): Linear(in_features=512, out_features=1024, bias=False) ) .. GENERATED FROM PYTHON SOURCE LINES 55-57 A minimal word-level tokenizer is enough for ``create_model`` to write the processing files next to the ONNX model. .. GENERATED FROM PYTHON SOURCE LINES 57-64 .. code-block:: Python tokenizer = PreTrainedTokenizerFast( tokenizer_object=Tokenizer(WordLevel(vocab={"": 0, "": 1, "": 2}, unk_token="")), bos_token="", eos_token="", unk_token="", ) .. GENERATED FROM PYTHON SOURCE LINES 65-69 Convert to ONNX with ``create_model`` ------------------------------------- The PyTorch model and tokenizer are saved to a folder, then converted to ONNX for the CPU execution provider in ``fp32`` precision. .. GENERATED FROM PYTHON SOURCE LINES 69-92 .. code-block:: Python from modelbuilder.builder import create_model # noqa: E402 work_dir = tempfile.mkdtemp(prefix="mbext_example_") model_dir = os.path.join(work_dir, "model") output_dir = os.path.join(work_dir, "onnx") cache_dir = os.path.join(work_dir, "cache") model.save_pretrained(model_dir) tokenizer.save_pretrained(model_dir) create_model( model_name="tiny-llama", input_path=model_dir, output_dir=output_dir, precision="fp32", execution_provider="cpu", cache_dir=cache_dir, num_hidden_layers=num_hidden_layers, ) onnx_path = os.path.join(output_dir, "model.onnx") print("ONNX model written to:", onnx_path) .. rst-class:: sphx-glr-script-out .. code-block:: none Writing model shards: 0%| | 0/1 [00:00` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_create_model_random_weights.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_create_model_random_weights.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_