### Run recommended environment setup script Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md After installation, run this script for recommended environment settings. ```bash source scripts/zentorch_env_setup.sh ``` -------------------------------- ### Run TorchAO LLM quantization examples Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/quantization/README.md Commands to run the W4A16 and da8w8 TorchAO LLM inference examples. Both scripts load pre-quantized models from the Hugging Face Hub, build a vLLM engine, and generate text for example prompts. ```bash python torchao/LLM/w4a16_example.py python torchao/LLM/da8w8_example.py ``` -------------------------------- ### Source environment setup scripts Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2/README.md Sources the zentorch environment setup script and the DLRM optimal environment setup script. ```shell source ../../../scripts/zentorch_env_setup.sh source ../../../scripts/dlrm_optimal_env_setup.sh ``` -------------------------------- ### Run LLM-Compressor quantization examples Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/quantization/README.md Commands to run the three LLM-Compressor vLLM inference examples for quantized LLMs. Each script loads an AMD-published checkpoint from the Hugging Face Hub. ```bash python LLM-Compressor/da8w8_example.py python LLM-Compressor/da8w4_example.py python LLM-Compressor/w4a16_example.py ``` -------------------------------- ### Install and Preload Performance Libraries Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Install tcmalloc and llvm-openmp and preload them via LD_PRELOAD for best performance. The llvm-openmp install path must be adjusted to your environment. ```bash # tcmalloc sudo apt-get install libtcmalloc-minimal4 export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4:$LD_PRELOAD # llvm-openmp conda install -c conda-forge llvm-openmp=18.1.8=hf5423f3_1 -y export LD_PRELOAD="/miniconda3/pkgs/llvm-openmp-18.1.8-hf5423f3_1/lib/libiomp5.so:$LD_PRELOAD" ``` -------------------------------- ### Build and install zentorch Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/vllm_fused_ffn_design.md Run the build script from the source tree to build and install zentorch, which ships the C++ op and the vLLM plugin. ```bash .claude/skills/build-zentorch-from-source/scripts/build.sh ``` -------------------------------- ### Install zentorch wheel file (v2.15.0.0) Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install the built wheel file for zentorch v2.15.0.0. ```bash pip install dist/zentorch-2.15.0.0-cp312-cp312-linux_x86_64.whl ``` -------------------------------- ### Install dependencies Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2-mlperf/README.md Runs the prepare_env.sh script to install dependencies. ```shell bash prepare_env.sh ``` -------------------------------- ### Install PyTorch v2.14.0 for build Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install PyTorch v2.14.0 (minimum) from the CPU index when building from source. ```bash pip install torch==2.14.0 --index-url https://download.pytorch.org/whl/cpu ``` -------------------------------- ### Install zentorch wheel file (v2.14.1.1) Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install the built wheel file for zentorch v2.14.1.1. ```bash pip install dist/zentorch-2.14.1.1-cp312-cp312-linux_x86_64.whl ``` -------------------------------- ### Install PyTorch v2.14.1 for build Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install PyTorch v2.14.1 from the CPU index when building from source. ```bash pip install torch==2.14.1 --index-url https://download.pytorch.org/whl/cpu ``` -------------------------------- ### Install zentorch wheel file (v2.14.0.3) Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install the built wheel file for zentorch v2.14.0.3. ```bash pip install dist/zentorch-2.14.0.3-cp312-cp312-linux_x86_64.whl ``` -------------------------------- ### Install zentorch v2.15.0.0 from PyPI Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install the matching zentorch version for PyTorch v2.15.0. ```bash pip install zentorch==2.15.0.0 ``` -------------------------------- ### Install PyTorch v2.15.0 (recommended) from PyPI Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install PyTorch v2.15.0 from the CPU index. This is the recommended PyTorch version for zentorch. ```bash pip install torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu ``` -------------------------------- ### Install PyTorch v2.14.0 and zentorch v2.14.0.3 from PyPI Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install PyTorch v2.14.0 (minimum supported) and the matching zentorch build. ```bash pip install torch==2.14.0 --index-url https://download.pytorch.org/whl/cpu pip install zentorch==2.14.0.3 ``` -------------------------------- ### Install PyTorch v2.14.1 and zentorch v2.14.1.1 from PyPI Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Install PyTorch v2.14.1 and the matching zentorch build. This is an alternative to the recommended v2.15.0. ```bash pip install torch==2.14.1 --index-url https://download.pytorch.org/whl/cpu pip install zentorch==2.14.1.1 ``` -------------------------------- ### Install Dependencies Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/transformers/bert/README.md Installs Python dependencies from requirements.txt. ```shell pip install -r requirements.txt ``` -------------------------------- ### View zentorch_env_setup.sh help Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/scripts/README.md Displays usage and options for the zentorch environment setup script. Run after activating the conda environment. ```bash source zentorch_env_setup.sh --help ``` -------------------------------- ### Install Unit Test Dependencies Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Run this command to install the dependencies required for unit tests. Before running any unit tests, export the environment variables ZENDNNL_ZP_COMP_CACHE=0 and ZENDNNL_ENABLE_POSTOP_CACHE=0 to disable ZenDNN caching. ```python python test/install_requirements.py ``` -------------------------------- ### Install and export jemalloc and llvm-openmp Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2/README.md Installs jemalloc and llvm-openmp for best performance. The LD_PRELOAD exports are optional because zentorch_env_setup.sh exports them. ```bash # jemalloc sudo apt install libjemalloc-dev export LD_PRELOAD=/usr/local/lib/libjemalloc.so:$LD_PRELOAD # optional as zentorch_env_setup.sh exports it # llvm-openmp conda install -c conda-forge llvm-openmp=18.1.8=hf5423f3_1 -y export LD_PRELOAD="$(conda info --base)/pkgs/llvm-openmp-18.1.8-hf5423f3_1/lib/libiomp5.so:$LD_PRELOAD" # optional as zentorch_env_setup.sh exports it ``` -------------------------------- ### Force W4A16 path in w4a16_example.py Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/quantization/README.md Sets the environment variable VLLM_CPU_INT4_W4A8 to "0" to force the W4A16 path. On Zen CPU the default is DA8W4 (VLLM_CPU_INT4_W4A8=1). ```python os.environ["VLLM_CPU_INT4_W4A8"] = "0" ``` -------------------------------- ### View dlrm_optimal_env_setup.sh help Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/scripts/README.md Displays usage and options for the DLRM environment setup script. Run after activating the conda environment. ```bash source dlrm_optimal_env_setup.sh --help ``` -------------------------------- ### Install zentorch from PyPI Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Installs the zentorch package from PyPI. The out-of-tree plugin takes precedence over the in-tree ZenCpuPlatform on supported AMD AVX512 systems. ```bash pip install zentorch ``` -------------------------------- ### Source optimal environment setup script Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2-mlperf/README.md Sources the dlrm_optimal_env_setup.sh script to set up the optimal performance environment. ```shell source ../../../scripts/dlrm_optimal_env_setup.sh ``` -------------------------------- ### Install scikit-learn dependency Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2/README.md Installs the scikit-learn package required for running the DLRMv2 benchmark. ```shell pip install scikit-learn ``` -------------------------------- ### Check zentorch version Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Use this command to verify the installed zentorch version. ```bash python -c 'import zentorch; print(zentorch.__version__)' ``` -------------------------------- ### vLLM Inference Example Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Basic usage of the plugin: create an LLM instance, set sampling parameters, and generate output. No code changes are required; the plugin is automatically detected. ```python from vllm import LLM, SamplingParams llm = LLM(model="meta-llama/Llama-3.1-8B", dtype="bfloat16") params = SamplingParams(temperature=0.8, top_p=0.95) output = llm.generate(["Hello, world!"], sampling_params=params) print(output) ``` -------------------------------- ### Install LMMS-Eval and dependencies for audio models Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README_ACCURACY.md Install LMMS-Eval and required audio dependencies for running audio models like LibriSpeech. ```bash pip install -e "git+https://github.com/EvolvingLMMs-Lab/lmms-eval.git#egg=lmms_eval" pip install "torchcodec==0.11.*" --index-url=https://download.pytorch.org/whl/cpu pip install editdistance jiwer librosa soundfile ``` -------------------------------- ### Pull Docker Image for Ubuntu Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Example command to pull the Docker image for Ubuntu 22.04 with vLLM 0.23.0 and zentorch 2.11.0.2. ```bash docker pull amdih/zendnn_zentorch:vllm_v0.23.0_zentorch_v2.11.0.2_ubuntu22.04_v2.11.0.2 ``` -------------------------------- ### Run and Enter Docker Container Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Starts a detached container with model volumes mounted, then opens an interactive shell and changes to the workspace directory. Mount volumes for model files and datasets; set VLLM_CPU_OMP_THREADS_BIND for your workload. ```bash docker run -d --name vllm_zentorch \ -v /path/to/models:/models \ amdih/zendnn_zentorch:vllm_v0.23.0_zentorch_v2.11.0.2_ubuntu22.04_v2.11.0.2 \ tail -f /dev/null docker exec -it vllm_zentorch bash cd workspace ``` -------------------------------- ### Run ResNet inference Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/README.md Run inference for the ResNet model using the resnet_example.py script. ```bash python resnet_example.py ``` -------------------------------- ### Uninstall existing zentorch Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Run this command to uninstall any existing zentorch installation before installing a new version. ```bash pip uninstall zentorch ``` -------------------------------- ### Run a single test file Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/AGENTS.md Runs a specific test file, for example test_bmm.py in the op_tests directory. ```bash python -m unittest test/unittests/op_tests/test_bmm.py ``` -------------------------------- ### OpenAI Python Client Usage Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Example of using the OpenAI Python client to interact with the local server. The SDK requires a non-empty API key, so a placeholder works when the server has no auth. ```APIDOC ## OpenAI Python Client Usage ### Description Example of using the OpenAI Python client to interact with the local server. The SDK requires a non-empty API key, so a placeholder works when the server has no auth. ### Method Client SDK ### Endpoint `http://localhost:/v1` (base URL) ### Parameters - **base_url** (string) - Required - The base URL of the local server, including `/v1`. - **api_key** (string) - Required - Any non-empty string (e.g., `"EMPTY"`) when the server has no auth. ### Response - **model** (string) - The model ID from `client.models.list().data[0].id`. - **chat.completions.create** - Returns a response with `choices[0].message.content`. - **completions.create** - Returns a response with `choices[0].text`. ### Request Example ```python from openai import OpenAI client = OpenAI(base_url="http://localhost:/v1", api_key="EMPTY") model = client.models.list().data[0].id # chat model: r = client.chat.completions.create( model=model, messages=[{"role": "user", "content": "Hello"}], max_tokens=128, temperature=0.7, ) print(r.choices[0].message.content) # base/prompt model: r = client.completions.create(model=model, prompt="Hello, world", max_tokens=128) print(r.choices[0].text) ``` ``` -------------------------------- ### Run DLRM inference Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/README.md Run inference for the DLRM model using the dlrm_example.py script. ```bash python dlrm_example.py ``` -------------------------------- ### Install lm-eval 0.4.12 Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README_ACCURACY.md Install the EleutherAI LM Evaluation Harness version 0.4.12 via pip. ```bash pip install lm-eval==0.4.12 ``` -------------------------------- ### Pull Docker Image for RHEL Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Example command to pull the Docker image for RHEL 9.5 with vLLM 0.23.0 and zentorch 2.11.0.2. ```bash docker pull amdih/zendnn_zentorch:vllm_v0.23.0_zentorch_v2.11.0.2_rhel9.5_v2.11.0.2 ``` -------------------------------- ### Run BF16 LLM inference Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/README.md Run vLLM inference for a BF16 LLM on CPU with zentorch using the bf16_llm_example.py script. ```bash python bf16_llm_example.py ``` -------------------------------- ### Run BERT inference Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/README.md Run inference for the BERT model using the bert_example.py script. ```bash python bert_example.py ``` -------------------------------- ### Invocation flow from vLLM startup to forward_cpu_zen Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/gdn/README.md Shows the call chain from vLLM startup through the plugin loader to the GatedDeltaNetPatch that installs forward_cpu_zen on QwenGatedDeltaNetAttention.forward_cpu. The CPU pipeline lives in _gdn_patch.py and dispatches to torch.ops.zentorch.gdn_* ops. ```text vLLM startup (in every process: driver / EngineCore / Worker) └── plugin loader fires `vllm.general_plugins` entry points └── zentorch.vllm:register └── manager.apply_all() └── GatedDeltaNetPatch.apply() └── zentorch.vllm._gdn_patch._apply_gdn_patch() │ (defers until qwen_gdn_linear_attn is imported, │ then installs the class-method override:) └── zentorch.vllm._gdn_patch._do_patch_gdn() └── QwenGatedDeltaNetAttention.forward_cpu ← forward_cpu_zen (the CPU pipeline lives in `_gdn_patch.py` and dispatches to torch.ops.zentorch.gdn_*) ``` -------------------------------- ### Enable Freezing Path with TORCHINDUCTOR_FREEZING Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Set the environment variable TORCHINDUCTOR_FREEZING=1 to enable model freezing before running the freezing path example. ```bash export TORCHINDUCTOR_FREEZING=1 ``` -------------------------------- ### Verify stable ABI library with torch-abi-audit Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/AGENTS.md Run this command to check that libzentorch_stable.so contains no ATen symbols, which would defeat its purpose. The tool is installed by test/install_requirements.py. ```bash torch-abi-audit -v build/lib.*/zentorch/libzentorch_stable.so ``` -------------------------------- ### Run lm_eval with vLLM for GSM8K Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README_ACCURACY.md Example command for running the GSM8K task with the Qwen3-30B-A3B-Instruct-2507 model using vLLM. Includes model arguments, task selection, and chat template application. ```bash lm_eval --model vllm \ --model_args pretrained=Qwen/Qwen3-30B-A3B-Instruct-2507,dtype=bfloat16,max_model_len=4096 \ --tasks gsm8k \ --batch_size auto \ --trust_remote_code \ --num_fewshot 5 \ --gen_kwargs "max_gen_toks=2048" \ --log_samples \ --output_path \ --apply_chat_template ``` -------------------------------- ### Run zentorch_env_setup.sh with options Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/scripts/README.md Sets optimal environment variables for zentorch CNN/RECSYS/LLM/NLP model runs. Requires a conda environment (not base) and supports frameworks zentorch, models llm/recsys/cnn/nlp, threads 96/128/192/256, and precision bf16_amp/bf16/fp32/woq/fp16. ```bash source zentorch_env_setup.sh --framework zentorch --model llm/recsys/cnn/nlp --threads 96/128/192/256 --precision bf16_amp/bf16/fp32/woq/fp16 ``` -------------------------------- ### Run dlrm_optimal_env_setup.sh with options Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/scripts/README.md Sets optimal environment variables for zentorch DLRM runs. Requires a conda environment (not base) and supports threads 96/128/192/256 and precision bf16/fp32/int8/fp16. ```bash source dlrm_optimal_env_setup.sh --threads 96/128/192/256 --precision bf16/fp32/int8/fp16 ``` -------------------------------- ### Disable zentorch fused FFN for TorchAO LLM Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/quantization/README.md Set the environment variable ZENTORCH_FUSED_FFN to "0" to disable zentorch fused FFN, required for both TorchAO LLM scripts. ```python os.environ["ZENTORCH_FUSED_FFN"] = "0" ``` -------------------------------- ### Build zentorch wheel file Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Build the wheel file using setup.py. The wheel is generated in the dist folder. ```bash python setup.py bdist_wheel ``` -------------------------------- ### Show DLRMv2 help options Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2/README.md Displays all available command-line options for main.py. ```shell python main.py --help ``` -------------------------------- ### Clean build artifacts Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Clean up build artifacts using setup.py clean --all. ```bash python setup.py clean --all ``` -------------------------------- ### ResNet output Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/README.md Expected output from the ResNet inference example. ```plain plane, carpenter's plane, woodworking plane ``` -------------------------------- ### DLRM output Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/examples/README.md Expected output from the DLRM inference example. ```plain AUC Score: 0.5 ``` -------------------------------- ### Stock vLLM CPU Container Launch (no zentorch) Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Runs vLLM with the official stock CPU image on pre-Zen4 EPYC (e.g., Milan) when zentorch is not available. Uses the same environment and flags as the zentorch container path, but the image's ENTRYPOINT is vllm serve, so pass model and options as arguments. ```bash RT="" $RT rm -f vllm-epyc 2>/dev/null $RT run -d --name vllm-epyc \ --ipc=host --network=host --cap-add=SYS_NICE \ \ --env VLLM_CPU_OMP_THREADS_BIND="$VLLM_CPU_OMP_THREADS_BIND" \ --env VLLM_CPU_KVCACHE_SPACE=$VLLM_CPU_KVCACHE_SPACE --env HF_TOKEN=${HF_TOKEN} \ vllm/vllm-openai-cpu:latest-x86_64 \ --dtype bfloat16 --port --max-model-len ``` -------------------------------- ### Detect CPU with scripts/detect.py Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Run from the project root to detect CPU properties. Add --host user@box for a remote host. Returns cpu_model, is_amd_epyc, epyc_generation, zen_arch, is_supported_epyc, avx512, logical_cores, physical_cores, sockets, numa_nodes, memory_gb. Use the output to route between zentorch and stock vLLM paths. ```bash python3 scripts/detect.py # add --host user@box for a remote host ``` -------------------------------- ### Estimate memory fit with estimate_memory.py Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Run this one-line command to check whether the model and KV cache fit in host RAM. Exit 0 means it fits, exit 1 means it does not. If fit.fits is false, do not launch; reduce --max-model-len to fit.suggested_max_model_len or use a smaller model. --max-model-len and --num-prompts are the knobs that move KV cache usage. --weight-gb overrides weights when HF metadata is missing. KV cache is bf16-only on zentorch CPU. ```bash python3 scripts/estimate_memory.py --model-id --revision --ram-gb --max-model-len <4096 or user value> --num-prompts <1 or desired concurrency> ``` -------------------------------- ### Container Launch with zentorch (docker/podman) Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Runs vLLM in a container using the zentorch image, with host networking, NUMA binding, and HF cache mount. Requires a free port and the resolved runtime from validate.py. Do not pass --device cpu on vLLM >= 0.20. ```bash RT="" $RT rm -f vllm-epyc 2>/dev/null # clear any leftover container from a prior run (name collision otherwise) $RT pull # agent pulls; do not ask the user to $RT run -d --name vllm-epyc \ # --ipc=host --network=host --cap-add=SYS_NICE (SYS_NICE = NUMA membind; NO --shm-size with --ipc=host) \ # resolved real path, e.g. -v /scratch/you/hf:/root/.cache/huggingface # --cpuset-cpus= --cpuset-mems= --env VLLM_CPU_OMP_THREADS_BIND="$VLLM_CPU_OMP_THREADS_BIND" \ --env VLLM_CPU_KVCACHE_SPACE=$VLLM_CPU_KVCACHE_SPACE \ --env HF_TOKEN=${HF_TOKEN} \ \ vllm serve --dtype bfloat16 --port --max-model-len ``` -------------------------------- ### Wrapper for process_weights_after_loading Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/vllm_fused_ffn_design.md Wraps vLLM's process_weights_after_loading to run fusion before the original quant-processing loop, preserving the required ordering. Falls back to native MLP on failure and logs a warning. ```python def _zen_process_weights_after_loading(model, *args, **kwargs): try: install_fused_mlp_forwards_for_model(model) # patch MLP.forward process_mlp_weights_after_loading(model) # build fused weights except Exception: logger.warning("[zentorch] fused MLP setup failed; using native MLP", exc_info=True) return orig_pwal(model, *args, **kwargs) # then quant processing ``` -------------------------------- ### Fusion Initialization dispatch_cpu_fused_mlp Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/vllm_fused_ffn_design.md Initializes MLP fusion by setting up mlp_module.cpu_mlp_forward. Skips if weights are empty or not 2D. Clones weights, prepares fused weights, stores them as module attributes, and optionally frees original weights. ```python def dispatch_cpu_fused_mlp( mlp_module: torch.nn.Module, activation_fn, num_experts: int = 1, remove_weights: bool = True ) -> None: """Initialize MLP fusion - sets up mlp_module.cpu_mlp_forward.""" # Check if weights are already empty (already fused or freed) if gate_up_weight.numel() == 0 or down_weight.numel() == 0: logger.debug_once("CPU MLP fusion: weights already empty, skipping") return # Check if weights are 2D if gate_up_weight.dim() != 2 or down_weight.dim() != 2: logger.debug_once("CPU MLP fusion: weights not 2D, skipping") return # Extract and clone weights w13_weight_data = gate_up_weight.clone().detach().contiguous() w2_weight_data = down_weight.clone().detach().contiguous() ... # Prepare fused weights w13, w2, w13_bias, w2_bias = prepare_fused_ffn_weights_from_merged(...) # Store fused weights as module attributes mlp_module._fused_w13_weight = w13 mlp_module._fused_w2_weight = w2 mlp_module._fused_w13_bias = w13_bias mlp_module._fused_w2_bias = w2_bias mlp_module._fused_activation = activation # Create fused forward function def fused_forward_fn(x): # Allocate output tensor (same shape as input) output = torch.empty_like(x) # Call the C++ out-variant op torch.ops.zentorch.zentorch_fused_ffn_concat.out( output, x, w13_weight=mlp_module._fused_w13_weight, w2_weight=mlp_module._fused_w2_weight, w13_bias=mlp_module._fused_w13_bias, w2_bias=mlp_module._fused_w2_bias, activation=mlp_module._fused_activation ) return output mlp_module.cpu_mlp_forward = fused_forward_fn # Free original weights if requested if remove_weights: mlp_module.gate_up_proj.weight = nn.Parameter(torch.empty(0), requires_grad=False) mlp_module.down_proj.weight = nn.Parameter(torch.empty(0), requires_grad=False) ``` -------------------------------- ### Create conda environment for vLLM Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Creates and activates a Python 3.12 conda environment named 'vllm-env' for vLLM installation. ```bash conda create -n vllm-env python=3.12 conda activate vllm-env ``` -------------------------------- ### Benchmarking with vLLM Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Run a throughput benchmark with FP8 KV-cache quantization enabled. The --kv-cache-dtype fp8_e4m3 flag is recommended for improved throughput. ```bash vllm bench throughput \ --model meta-llama/Llama-3.1-8B \ --kv-cache-dtype fp8_e4m3 \ --random-input-len 128 \ --random-output-len 128 \ --num-prompts 100 ``` -------------------------------- ### Run all tests with unittest Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/AGENTS.md Runs the full test suite using Python's unittest discovery from the ./test directory. ```bash python -m unittest discover -s ./test ``` -------------------------------- ### Check zentorch build config Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Use this command to display the build configuration of zentorch. ```bash python -c 'import zentorch; print(*zentorch.__config__.split("\n"), sep="\n")' ``` -------------------------------- ### Activation Mapping and _get_activation_string Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/vllm_fused_ffn_design.md Maps vLLM activation classes to zentorch activation strings. Returns None for unsupported activations. ```python ACTIVATION_MAPPING = { 'SiluAndMul': 'silu', 'GeluAndMul': 'gelu', 'NewGELU': 'gelu_tanh', } def _get_activation_string(act_fn) -> Optional[str]: """Convert vLLM activation function to zentorch activation string.""" if act_fn is None: return None act_name = type(act_fn).__name__ return ACTIVATION_MAPPING.get(act_name) ``` -------------------------------- ### Profiling with vLLM Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Run a throughput benchmark with profiling enabled. Avoid using --profile for benchmarking as it impacts results; use it only for operator-level metrics. ```bash export VLLM_TORCH_PROFILER_DIR="." vllm bench throughput \ --model meta-llama/Llama-3.1-8B \ --kv-cache-dtype fp8_e4m3 \ --random-input-len 128 \ --random-output-len 128 \ --num-prompts 10 \ --profile ``` -------------------------------- ### Pull Docker Image with Placeholder Tags Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/src/cpu/python/zentorch/vllm/README.md Pulls the pre-built Docker image with vLLM and zentorch. Replace , , , and with desired values. Available OS tags are ubuntu22.04 and rhel9.5. ```bash docker pull amdih/zendnn_zentorch:vllm_v_zentorch_v__ ``` -------------------------------- ### Configure CPU and socket settings Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2/README.md Sets environment variables for a 2-socket machine with 256 cores per socket. Adjust these values to match your machine's specifications. ```shell ## This configuration is for a 2-socket machine with 256 cores per socket. Adjust it for your machine. export NUM_SOCKETS=2 # e.g., 2 export CPUS_PER_SOCKET=256 # e.g., 256 export CPUS_PER_INSTANCE=2 # instance-per-process number=CPUS_PER_PROCESS/CPUS_PER_INSTANCE # total-instance = instance-per-process * process-per-socket export CPUS_FOR_LOADGEN=1 # number of CPUs for loadgen # finally used in our code is max(CPUS_FOR_LOADGEN, remaining cores for instances) ``` -------------------------------- ### Generic MLP Detection and Fusion Installation Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/vllm_fused_ffn_design.md Detects MLP modules structurally (Pattern A or Pattern B) and patches forward methods or builds fused weights. Used by the wrapper to enable fusion before weights are freed. ```python def _is_mlp_module(module): """Structural MLP detection (Pattern A or Pattern B).""" has_pattern_a = hasattr(module, "gate_up_proj") and hasattr(module, "down_proj") has_pattern_b = ( hasattr(module, "gate_proj") and hasattr(module, "up_proj") and hasattr(module, "down_proj") ) return has_pattern_a or has_pattern_b def install_fused_mlp_forwards_for_model(model): """Patch `forward` on every detected MLP class in the model.""" patched_classes = set() for module in model.modules(): if _is_mlp_module(module): mlp_class = type(module) if mlp_class not in patched_classes: install_fused_mlp_forward(mlp_class) patched_classes.add(mlp_class) def process_mlp_weights_after_loading(model): """Build fused weights for every eligible MLP module.""" for module in model.modules(): if _is_mlp_module(module): act_fn = getattr(module, "act_fn", None) num_experts = getattr(module, "num_experts", 1) dispatch_cpu_fused_mlp(module, act_fn, num_experts, remove_weights=True) ``` -------------------------------- ### End-to-end test with vLLM and ZENTORCH_FUSED_FFN Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/vllm_fused_ffn_design.md Enable the vLLM MLP fusion by setting ZENTORCH_FUSED_FFN=1 and run a simple generation with Llama-3.1-8B on CPU. ```bash ZENTORCH_FUSED_FFN=1 python -c " from vllm import LLM llm = LLM(model='meta-llama/Llama-3.1-8B', device='cpu') print(llm.generate('Hello, world!')) " ``` -------------------------------- ### Modify setup_env_offline.sh configuration Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2-mlperf/README.md Shows the configuration variables to modify in setup_env_offline.sh to match the machine's specifications. Includes NUM_SOCKETS, CPUS_PER_SOCKET, CPUS_PER_PROCESS, CPUS_PER_INSTANCE, CPUS_FOR_LOADGEN, and BATCH_SIZE. ```shell export NUM_SOCKETS=2 # e.g., 2 export CPUS_PER_SOCKET=256 # e.g., 256 export CPUS_PER_PROCESS=256 # determines the number of processes used # process-per-socket = CPUS_PER_SOCKET/CPUS_PER_PROCESS export CPUS_PER_INSTANCE=2 # instance-per-process number=CPUS_PER_PROCESS/CPUS_PER_INSTANCE # total-instance = instance-per-process * process-per-socket export CPUS_FOR_LOADGEN=1 # number of CPUs for loadgen # finally used in our code is max(CPUS_FOR_LOADGEN, remaining cores for instances) export BATCH_SIZE=100 ``` -------------------------------- ### Profiler output for zentorch_linear_unary and zentorch_linear_tanh Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Example profiler output showing the umbrella function zentorch::zentorch_linear_unary with a low Self CPU of 134.041us but a high CPU total of 22.196ms, and the inner fused operation zentorch::zentorch_linear_tanh with Self CPU of 33.491us and CPU total of 92.271us. ```text Name Self CPU % Self CPU CPU total % CPU total --------------------------------------------------------------------------------------- zentorch::zentorch_linear_unary 0.29% 134.041us 47.74% 22.196ms zentorch::zentorch_linear_tanh 0.07% 33.491us 0.20% 92.271us ``` -------------------------------- ### Run full GDN test suite with unittest discover Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/gdn/README.md Runs the entire GDN unittest suite from the repo root. The -t . (top-level dir) is required so absolute imports (from test.unittests.op_tests.layers.gdn...) resolve. ```bash python -m unittest discover -s test/unittests/op_tests/layers/gdn -t . -v ``` -------------------------------- ### POST /v1/completions Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/reference.md Takes a raw prompt (no template) and returns the generated text. Use this endpoint for base text models without a chat template, or when the template status is ambiguous or unknown. ```APIDOC ## POST /v1/completions ### Description Takes a raw `prompt` (no template) and returns `choices[0].text`. ### Method POST ### Endpoint /v1/completions ### Parameters #### Request Body - `prompt` (string) - Required - The raw prompt. - `max_tokens` (integer) - Optional - Output-token cap. `prompt_tokens + max_tokens` must be `<= --max-model-len`. - `temperature` (number) - Optional - Randomness; `0` is deterministic/greedy. - `top_p` (number) - Optional - Nucleus sampling; tune this **or** `temperature`, not both. - `stream` (boolean) - Optional - `true` streams tokens over SSE instead of one blocking reply. - `stop` (string or array) - Optional - String(s) that end generation early. ### Response #### Success Response (200) - `choices[0].text` (string) - The generated text. ``` -------------------------------- ### Clone ZenDNN-pytorch-plugin repository Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Clone the repository and change into the directory to build from source. ```bash git clone https://github.com/amd/ZenDNN-pytorch-plugin.git cd ZenDNN-pytorch-plugin ``` -------------------------------- ### Run DLRMv2 benchmark for performance Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/recsys/dlrmv2/README.md Executes main.py to generate performance numbers. Replace DATA_DIR and MODEL_DIR with the actual paths. ```shell python main.py --dataset_path= --model_path= ``` -------------------------------- ### Run pre-trained model tests Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/AGENTS.md Runs the pre-trained model tests located in ./test/pre_trained_model_tests. ```bash python -m unittest discover -s ./test/pre_trained_model_tests ``` -------------------------------- ### Conda/Host Launch with numactl Prefix Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Launches vLLM directly on the host using the conda environment, with the launch prefix from cpu_tune to bind memory to the chosen socket. The prefix may be empty, meaning unpinned. ```bash vllm serve --dtype bfloat16 --port --max-model-len & # e.g. numactl --cpunodebind=0 --membind=0 vllm serve ... ``` -------------------------------- ### Run validate.py with image, generation, and AVX-512 flags Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Validates the runtime and environment before launching. Hard-enforces the AVX-512 gate: on a CPU without AVX-512, returns a blocking error (ready: false) and stops the flow. Reads the local CPU if --avx512 is omitted. Returns fields like ready, requires_confirmation, zentorch_capable, runtime, compatibility, and hf_cache. Do not proceed if ready is false. ```bash python3 scripts/validate.py --image --generation --avx512 ``` -------------------------------- ### Free Port Selection Loop Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Selects a free TCP port before launching vLLM with --network=host, where a busy port is a hard failure. The loop increments the port until ss reports no LISTEN socket. ```bash PORT=8000; while ss -ltn "sport = :$PORT" | grep -q LISTEN; do PORT=$((PORT+1)); done ``` -------------------------------- ### Enable ZenDNN profiling with ZENDNNL_ENABLE_PROFILER Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Set the environment variable ZENDNNL_ENABLE_PROFILER to 1 to enable profiling logs for ZenDNN. ```bash export ZENDNNL_ENABLE_PROFILER=1 ``` -------------------------------- ### Run Multi-Instance Benchmark Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/transformers/bert/README.md Executes the multi-instance accuracy benchmark script with the specified system type and output file. ```shell ./run_tests_M-inst_VM_ZenDNN-510.sh Genoa-96 results.txt ``` -------------------------------- ### Size CPU runtime with cpu_tune.py Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Run this command to export environment variables for a single-socket vLLM CPU runtime. It exports VLLM_CPU_OMP_THREADS_BIND and VLLM_CPU_KVCACHE_SPACE, sized from the chosen socket's local RAM. It does not set OMP_NUM_THREADS or VLLM_CPU_NUM_OF_RESERVED_CPU. Use --format json to inspect the output. The script also emits container_cpuset and conda_launch_prefix for the chosen socket; surface any warning to the user. ```bash eval "$(python3 scripts/cpu_tune.py)" # or --format json to inspect ``` -------------------------------- ### Run Single Instance Benchmark Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/benchmark/transformers/bert/README.md Executes the single-instance performance benchmark script with the specified system type and output file. ```shell ./run_tests_1-inst_VM_ZenDNN-510.sh Genoa-96 results.txt ``` -------------------------------- ### Run tests by file pattern Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/AGENTS.md Runs unit tests whose file names match the pattern 'test_mm*'. ```bash python -m unittest discover -s ./test/unittests -p "test_mm*" ``` -------------------------------- ### ZENTORCH_TWO_PASS split diagram Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/zentorch_fused_moe.md Shows the two backend calls when ZENTORCH_TWO_PASS=1: Call 1 performs W13 + gated activation only, Call 2 performs W2 + MoE weighted-reduce. Requires ZENTORCH_MOE_ROUTED=0 to be selectable. ```text ZENTORCH_TWO_PASS=1 ├─ Call 1: W13 + gated activation only │ gemm_outputs = per-expert [M_e, N] buffers (kernel writes the gated │ result into the first I = N/2 columns) │ w2_weights = {} moe_output = None row_ptrs = None │ → produces the activated intermediate, no W2, no reduce │ └─ Call 2: W2 + MoE weighted-reduce only inputs = first I columns of Call 1's output, made contiguous w13_weights = w2 slices (W2 is handed in as the only matmul) gemm_outputs = grouped_inputs (so the pre-built row_ptrs still target the correct W2 destination rows) activation = "none" moe_output = output row_ptrs = row_ptrs → down projection + router-weighted reduce into output ``` -------------------------------- ### Run LLM tests Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/test/README.md Discovers and runs all tests in the ./test/llm_tests directory. ```bash python -m unittest discover -s ./test/llm_tests ``` -------------------------------- ### Run check_model.py to validate model support Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Use this command to check if vLLM supports the specified model. Exit 0 means the model can be served as a generation endpoint or support is undeterminable; exit 1 means the model is not supported (e.g., pooling/embedding/reranker, multimodal without chat template). The result provides the client endpoint (primary_endpoint) and chat template details. ```bash python3 scripts/check_model.py --model-id --revision --vllm-version ``` -------------------------------- ### Macro-Benchmark: benchmark_latency.py Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/docs/vllm/vllm_fused_ffn_design.md Run the end-to-end inference latency benchmark using vLLM with a Llama-3.1-8B model on CPU. Use this to measure overall latency improvements from fusion. ```bash cd /proj/rdi/staff/armukhop/vllm python benchmarks/benchmark_latency.py \ --model meta-llama/Llama-3.1-8B \ --batch-size 1 \ --input-len 512 \ --output-len 128 \ --device cpu ``` -------------------------------- ### OpenAI Python client usage Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/skills/serving-llms-on-epyc/SKILL.md Python client for both chat and completions endpoints. Point base_url at the local server; the SDK requires a non-empty key, so any placeholder works when the server has no auth. ```python from openai import OpenAI client = OpenAI(base_url="http://localhost:/v1", api_key="EMPTY") model = client.models.list().data[0].id # chat model: r = client.chat.completions.create( model=model, messages=[{"role": "user", "content": "Hello"}], max_tokens=128, temperature=0.7, ) print(r.choices[0].message.content) # base/prompt model: r = client.completions.create(model=model, prompt="Hello, world", max_tokens=128) print(r.choices[0].text) ``` -------------------------------- ### ChartQA evaluation for instruct/chat models Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README_ACCURACY.md Run ChartQA vision-language benchmark with vllm-vlm for instruct/chat models. Includes --apply_chat_template. ```bash lm_eval --model vllm-vlm \ --model_args pretrained=,dtype=bfloat16 \ --tasks chartqa \ --batch_size auto \ --trust_remote_code \ --apply_chat_template \ --log_samples \ --output_path ``` -------------------------------- ### Run tests by name pattern Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/AGENTS.md Runs unit tests whose names match the pattern 'woq'. ```bash python -m unittest discover -s ./test/unittests -k "woq" ``` -------------------------------- ### ChartQA evaluation for base models Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README_ACCURACY.md Run ChartQA vision-language benchmark with vllm-vlm for non-instruct (base) models. Do not use --apply_chat_template. ```bash lm_eval --model vllm-vlm \ --model_args pretrained=,dtype=bfloat16 \ --tasks chartqa \ --batch_size auto \ --trust_remote_code \ --log_samples \ --output_path ``` -------------------------------- ### Create conda environment for build Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Create and activate a conda environment named 'pt-zentorch' with Python 3.12 for building from source. ```bash conda create -n pt-zentorch python=3.12 -y conda activate pt-zentorch ``` -------------------------------- ### Optimize HuggingFace NLP models with torch.compile Source: https://github.com/amd/zendnn-pytorch-plugin/blob/main/README.md Use torch.compile with the 'zentorch' backend to optimize HuggingFace NLP models. Wrap inference in torch.no_grad() to reduce memory usage and improve performance. ```python model = torch.compile(model, backend='zentorch') with torch.no_grad(): output = model(input) ```