diff --git a/docs/data/how-to/fine-tuning-llms/attention-module.png b/docs/data/how-to/fine-tuning-llms/attention-module.png new file mode 100644 index 0000000000..2bd9834566 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/attention-module.png differ diff --git a/docs/data/how-to/fine-tuning-llms/ck-comparisons.jpg b/docs/data/how-to/fine-tuning-llms/ck-comparisons.jpg new file mode 100644 index 0000000000..07db2eaba2 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/ck-comparisons.jpg differ diff --git a/docs/data/how-to/fine-tuning-llms/ck-compilation.jpg b/docs/data/how-to/fine-tuning-llms/ck-compilation.jpg new file mode 100644 index 0000000000..3503bcc65f Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/ck-compilation.jpg differ diff --git a/docs/data/how-to/fine-tuning-llms/ck-inference_flow.jpg b/docs/data/how-to/fine-tuning-llms/ck-inference_flow.jpg new file mode 100644 index 0000000000..5548ade6c9 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/ck-inference_flow.jpg differ diff --git a/docs/data/how-to/fine-tuning-llms/ck-kernel_launch.jpg b/docs/data/how-to/fine-tuning-llms/ck-kernel_launch.jpg new file mode 100644 index 0000000000..3947a5615f Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/ck-kernel_launch.jpg differ diff --git a/docs/data/how-to/fine-tuning-llms/ck-operation_flow.jpg b/docs/data/how-to/fine-tuning-llms/ck-operation_flow.jpg new file mode 100644 index 0000000000..3389f4c7c7 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/ck-operation_flow.jpg differ diff --git a/docs/data/how-to/fine-tuning-llms/ck-root_instance.jpg b/docs/data/how-to/fine-tuning-llms/ck-root_instance.jpg new file mode 100644 index 0000000000..f225dde3e9 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/ck-root_instance.jpg differ diff --git a/docs/data/how-to/fine-tuning-llms/ck-template_parameters.jpg b/docs/data/how-to/fine-tuning-llms/ck-template_parameters.jpg new file mode 100644 index 0000000000..8876965ef7 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/ck-template_parameters.jpg differ diff --git a/docs/data/how-to/fine-tuning-llms/compute-unit.png b/docs/data/how-to/fine-tuning-llms/compute-unit.png new file mode 100644 index 0000000000..e6c1f2eb07 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/compute-unit.png differ diff --git a/docs/data/how-to/fine-tuning-llms/occupancy-vgpr.png b/docs/data/how-to/fine-tuning-llms/occupancy-vgpr.png new file mode 100644 index 0000000000..270bc7a349 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/occupancy-vgpr.png differ diff --git a/docs/data/how-to/fine-tuning-llms/omniperf-analysis.png b/docs/data/how-to/fine-tuning-llms/omniperf-analysis.png new file mode 100644 index 0000000000..6a8c522725 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/omniperf-analysis.png differ diff --git a/docs/data/how-to/fine-tuning-llms/omnitrace-timeline.png b/docs/data/how-to/fine-tuning-llms/omnitrace-timeline.png new file mode 100644 index 0000000000..106d1ba76a Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/omnitrace-timeline.png differ diff --git a/docs/data/how-to/fine-tuning-llms/perfetto-trace.svg b/docs/data/how-to/fine-tuning-llms/perfetto-trace.svg new file mode 100644 index 0000000000..80c676cd0b --- /dev/null +++ b/docs/data/how-to/fine-tuning-llms/perfetto-trace.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/docs/data/how-to/fine-tuning-llms/profiling-perfetto-ui.png b/docs/data/how-to/fine-tuning-llms/profiling-perfetto-ui.png new file mode 100644 index 0000000000..09262f8a7f Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/profiling-perfetto-ui.png differ diff --git a/docs/data/how-to/fine-tuning-llms/tunableop.png b/docs/data/how-to/fine-tuning-llms/tunableop.png new file mode 100644 index 0000000000..3564ca80a2 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/tunableop.png differ diff --git a/docs/data/how-to/fine-tuning-llms/vllm-single-gpu-log.png b/docs/data/how-to/fine-tuning-llms/vllm-single-gpu-log.png new file mode 100644 index 0000000000..1d00b91902 Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/vllm-single-gpu-log.png differ diff --git a/docs/data/how-to/fine-tuning-llms/weight-update.png b/docs/data/how-to/fine-tuning-llms/weight-update.png new file mode 100644 index 0000000000..d8f2b9b7df Binary files /dev/null and b/docs/data/how-to/fine-tuning-llms/weight-update.png differ diff --git a/docs/how-to/deep-learning-rocm.rst b/docs/how-to/deep-learning-rocm.rst index 49c0b5d99f..d638e1cb3c 100644 --- a/docs/how-to/deep-learning-rocm.rst +++ b/docs/how-to/deep-learning-rocm.rst @@ -60,6 +60,9 @@ Find information on version compatibility and framework release notes in :doc:`T For guidance on installing ROCm itself, refer to :doc:`ROCm installation for Linux `. -Learn how to use your ROCm deep learning environment for training, fine-tuning, and inference through the following guides. +Learn how to use your ROCm deep learning environment for training, fine-tuning, inference, and performance optimization +through the following guides. * :doc:`rocm-for-ai/index` + +* :doc:`fine-tuning-llms/index` diff --git a/docs/how-to/fine-tuning-llms/fine-tuning-and-inference.rst b/docs/how-to/fine-tuning-llms/fine-tuning-and-inference.rst new file mode 100644 index 0000000000..0c0251fd1e --- /dev/null +++ b/docs/how-to/fine-tuning-llms/fine-tuning-and-inference.rst @@ -0,0 +1,20 @@ +.. meta:: + :description: How to fine-tune LLMs with ROCm + :keywords: ROCm, LLM, fine-tuning, inference, usage, tutorial + +************************* +Fine-tuning and inference +************************* + +Fine-tuning using ROCm involves leveraging AMD's GPU-accelerated :doc:`libraries ` and +:doc:`tools ` to optimize and train deep learning models. ROCm provides a comprehensive +ecosystem for deep learning development, including open-source libraries for optimized deep learning operations and +ROCm-aware versions of :doc:`deep learning frameworks <../deep-learning-rocm>` such as PyTorch, TensorFlow, and JAX. + +Single-accelerator systems, such as a machine equipped with a single accelerator or GPU, are commonly used for +smaller-scale deep learning tasks, including fine-tuning pre-trained models and running inference on moderately +sized datasets. See :doc:`single-gpu-fine-tuning-and-inference`. + +Multi-accelerator systems, on the other hand, consist of multiple accelerators working in parallel. These systems are +typically used in LLMs and other large-scale deep learning tasks where performance, scalability, and the handling of +massive datasets are crucial. See :doc:`multi-gpu-fine-tuning-and-inference`. diff --git a/docs/how-to/fine-tuning-llms/index.rst b/docs/how-to/fine-tuning-llms/index.rst new file mode 100644 index 0000000000..c197158f28 --- /dev/null +++ b/docs/how-to/fine-tuning-llms/index.rst @@ -0,0 +1,37 @@ +.. meta:: + :description: How to fine-tune LLMs with ROCm + :keywords: ROCm, LLM, fine-tuning, usage, tutorial + +************************** +Fine-tuning LLMs with ROCm +************************** + +ROCm empowers the fine-tuning and optimization of large language models, making them accessible and efficient for +specialized tasks. ROCm supports the broader AI ecosystem to ensure seamless integration with open frameworks, +models, and tools. + +For more information, see `What is ROCm? `_ + +Throughout the following topics, this guide discusses the goals and :ref:`challenges of fine-tuning a large language +model ` like Llama 2. Then, it introduces :ref:`common methods of optimizing your +fine-tuning ` using techniques like LoRA with libraries like PEFT. In the +sections that follow, you'll find practical guides on libraries and tools to accelerate your fine-tuning. + +- :doc:`Conceptual overview of fine-tuning LLMs ` + +- :doc:`Fine-tuning and inference ` using a + :doc:`single-accelerator ` or + :doc:`multi-accelerator ` system. + +- :doc:`Model quantization ` + +- :doc:`Model acceleration libraries ` + +- :doc:`LLM inference frameworks ` + +- :doc:`Optimizing with Composable Kernel ` + +- :doc:`Optimizing Triton kernels ` + +- :doc:`Profiling and debugging ` + diff --git a/docs/how-to/fine-tuning-llms/llm-inference-frameworks.rst b/docs/how-to/fine-tuning-llms/llm-inference-frameworks.rst new file mode 100644 index 0000000000..9da634d5cc --- /dev/null +++ b/docs/how-to/fine-tuning-llms/llm-inference-frameworks.rst @@ -0,0 +1,218 @@ +.. meta:: + :description: How to fine-tune LLMs with ROCm + :keywords: ROCm, LLM, fine-tuning, usage, tutorial, inference, vLLM, TGI, text generation inference + +************************ +LLM inference frameworks +************************ + +This section discusses how to implement `vLLM `_ and `Hugging Face TGI +`_ using +:doc:`single-accelerator ` and +:doc:`multi-accelerator ` systems. + +.. _fine-tuning-llms-vllm: + +vLLM inference +============== + +vLLM is renowned for its paged attention algorithm that can reduce memory consumption and increase throughput thanks to +its paging scheme. Instead of allocating GPU high-bandwidth memory (HBM) for the maximum output token lengths of the +models, the paged attention of vLLM allocates GPU HBM dynamically for its actual decoding lengths. This paged attention +is also effective when multiple requests share the same key and value contents for a large value of beam search or +multiple parallel requests. + +vLLM also incorporates many modern LLM acceleration and quantization algorithms, such as Flash Attention, HIP and CUDA +graphs, tensor parallel multi-GPU, GPTQ, AWQ, and token speculation. + +Installing vLLM +--------------- + +1. To install vLLM, run the following commands. + + .. code-block:: shell + + # Install from the source + git clone https://github.com/ROCm/vllm.git + cd vllm + PYTORCH_ROCM_ARCH=gfx942 python setup.py install #MI300 series + +.. _fine-tuning-llms-vllm-rocm-docker-image: + +2. Run the following commands to build a Docker image ``vllm-rocm``. + + .. code-block:: shell + + git clone https://github.com/vllm-project/vllm.git + cd vllm + docker build -f Dockerfile.rocm -t vllm-rocm . + +.. tab-set:: + + .. tab-item:: vLLM on a single-accelerator system + :sync: single + + 3. To use vLLM as an API server to serve reference requests, first start a container using the :ref:`vllm-rocm + Docker image `. + + .. code-block:: shell + + docker run -it \ + --network=host \ + --group-add=video \ + --ipc=host \ + --cap-add=SYS_PTRACE \ + --security-opt seccomp=unconfined \ + --device /dev/kfd \ + --device /dev/dri \ + -v :/app/model \ + vllm-rocm \ + bash + + 4. Inside the container, start the API server to run on a single accelerator on port 8000 using the following command. + + .. code-block:: shell + + python -m vllm.entrypoints.api_server --model /app/model --dtype float16 --port 8000 & + + The following log message is displayed in your command line indicates that the server is listening for requests. + + .. image:: ../../data/how-to/fine-tuning-llms/vllm-single-gpu-log.png + :alt: vLLM API server log message + :align: center + + 5. To test, send it a curl request containing a prompt. + + .. code-block:: shell + + curl http://localhost:8000/generate -H "Content-Type: application/json" -d '{"prompt": "What is AMD Instinct?", "max_tokens": 80, "temperature": 0.0 }' + + You should receive a response like the following. + + .. code-block:: text + + {"text":["What is AMD Instinct?\nAmd Instinct is a brand new line of high-performance computing (HPC) processors from Advanced Micro Devices (AMD). These processors are designed to deliver unparalleled performance for HPC workloads, including scientific simulations, data analytics, and machine learning.\nThe Instinct lineup includes a range of processors, from the entry-level Inst"]} + + .. tab-item:: vLLM on a multi-accelerator system + :sync: multi + + 3. To use vLLM as an API server to serve reference requests, first start a container using the :ref:`vllm-rocm + Docker image `. + + .. code-block:: shell + + docker run -it \ + --network=host \ + --group-add=video \ + --ipc=host \ + --cap-add=SYS_PTRACE \ + --security-opt seccomp=unconfined \ + --device /dev/kfd \ + --device /dev/dri \ + -v :/app/model \ + vllm-rocm \ + bash + + + 4. To run API server on multiple GPUs, use the ``-tp`` or ``--tensor-parallel-size`` parameter. For example, to use two + GPUs, start the API server using the following command. + + .. code-block:: shell + + python -m vllm.entrypoints.api_server --model /app/model --dtype float16 -tp 2 --port 8000 & + + 5. To run multiple instances of API Servers, specify different ports for each server, and use ``ROCR_VISIBLE_DEVICES`` to + isolate each instance to a different accelerator. + + For example, to run two API servers, one on port 8000 using GPU 0 and 1, one on port 8001 using GPU 2 and 3, use a + a command like the following. + + .. code-block:: shell + + ROCR_VISIBLE_DEVICES=0,1 python -m vllm.entrypoints.api_server --model /data/llama-2-7b-chat-hf --dtype float16 –tp 2 --port 8000 & + ROCR_VISIBLE_DEVICES=2,3 python -m vllm.entrypoints.api_server --model /data/llama-2-7b-chat-hf --dtype float16 –tp 2--port 8001 & + + 6. To test, send it a curl request containing a prompt. + + .. code-block:: shell + + curl http://localhost:8000/generate -H "Content-Type: application/json" -d '{"prompt": "What is AMD Instinct?", "max_tokens": 80, "temperature": 0.0 }' + + You should receive a response like the following. + + .. code-block:: text + + {"text":["What is AMD Instinct?\nAmd Instinct is a brand new line of high-performance computing (HPC) processors from Advanced Micro Devices (AMD). These processors are designed to deliver unparalleled performance for HPC workloads, including scientific simulations, data analytics, and machine learning.\nThe Instinct lineup includes a range of processors, from the entry-level Inst"]} + +.. _fine-tuning-llms-tgi: + +Hugging Face TGI +================ + +Text Generation Inference (TGI) is LLM serving framework from Hugging +Face, and it also supports the majority of high-performance LLM +acceleration algorithms such as Flash Attention, Paged Attention, +CUDA/HIP graph, tensor parallel multi-GPU, GPTQ, AWQ, and token +speculation. + +.. tip:: + + In addition to LLM serving capability, TGI also provides the `Text Generation Inference benchmarking tool + `_. + +Install TGI +----------- + +1. To install the TGI Docker image, run the following commands. + + .. code-block:: shell + + # Install from Dockerfile + git clone https://github.com/huggingface/text-generation-inference.git -b mi300-compat + cd text-generation-inference + docker build . -f Dockerfile.rocm + +.. tab-set:: + + .. tab-item:: TGI on a single-accelerator system + :sync: single + + 2. Launch a model using TGI server on a single accelerator. + + .. code-block:: shell + + export ROCM_USE_FLASH_ATTN_V2_TRITON=True + text-generation-launcher --model-id NousResearch/Meta-Llama-3-70B --dtype float16 --port 8000 & + + 3. To test, send it a curl request containing a prompt. + + .. code-block:: shell + + curl http://localhost:8000/generate_stream -X POST -d '{"inputs":"What is AMD Instinct?","parameters":{"max_new_tokens":20}}' -H 'Content-Type: application/json' + + You should receive a response like the following. + + .. code-block:: shell + + data:{"index":20,"token":{"id":304,"text":" in","logprob":-1.2822266,"special":false},"generated_text":" AMD Instinct is a new family of data center GPUs designed to accelerate the most demanding workloads in","details":null} + + .. tab-item:: TGI on a multi-accelerator system + + 2. Launch a model using TGI server on multiple accelerators (4 in this case). + + .. code-block:: shell + + export ROCM_USE_FLASH_ATTN_V2_TRITON=True + text-generation-launcher --model-id NousResearch/Meta-Llama-3-8B --dtype float16 --port 8000 --num-shard 4 & + + 3. To test, send it a curl request containing a prompt. + + .. code-block:: shell + + curl http://localhost:8000/generate_stream -X POST -d '{"inputs":"What is AMD Instinct?","parameters":{"max_new_tokens":20}}' -H 'Content-Type: application/json' + + You should receive a response like the following. + + .. code-block:: shell + + data:{"index":20,"token":{"id":304,"text":" in","logprob":-1.2773438,"special":false},"generated_text":" AMD Instinct is a new family of data center GPUs designed to accelerate the most demanding workloads in","details":null} diff --git a/docs/how-to/fine-tuning-llms/model-acceleration-libraries.rst b/docs/how-to/fine-tuning-llms/model-acceleration-libraries.rst new file mode 100644 index 0000000000..f1bc7c7046 --- /dev/null +++ b/docs/how-to/fine-tuning-llms/model-acceleration-libraries.rst @@ -0,0 +1,249 @@ +.. meta:: + :description: How to fine-tune LLMs with ROCm + :keywords: ROCm, LLM, fine-tuning, usage, tutorial, Flash Attention, Hugging Face, xFormers, vLLM, PyTorch + +**************************** +Model acceleration libraries +**************************** + +This section discusses model acceleration techniques and libraries to improve memory efficiency and performance. + +Flash Attention 2 +================= + +Flash Attention is a technique designed to reduce memory movements between GPU SRAM and high-bandwidth memory (HBM). By +using a tiling approach, Flash Attention 2 improves memory locality in the nested loops of query, key, and value +computations within the Attention modules of LLMs. These modules include Multi-Head Attention (MHA), Group-Query +Attention (GQA), and Multi-Query Attention (MQA). This reduction in memory movements significantly decreases the +time-to-first-token (TTFT) latency for large batch sizes and long prompt sequences, thereby enhancing overall +performance. + +.. image:: ../../data/how-to/fine-tuning-llms/attention-module.png + :alt: Attention module of a large language module utilizing tiling + :align: center + +Installing Flash Attention 2 +---------------------------- + +ROCm provides two different implementations of Flash Attention 2 modules. They can be deployed interchangeably: + +* ROCm `Composable Kernel `_ + (CK) Flash Attention 2 + +* `OpenAI Triton `_ Flash Attention 2 + +.. tab-set:: + + .. tab-item:: CK Flash Attention 2 + + To install CK Flash Attention 2, use the following commands. + + .. code-block:: shell + + # Install from the source + git clone https://github.com/ROCm/flash-attention.git + cd flash-attention/ + GPU_ARCHS=gfx942 python setup.py install #MI300 series + + Hugging Face Transformers can easily deploy the CK Flash Attention 2 module by passing an argument + ``attn_implementation="flash_attention_2"`` in the ``from_pretrained`` class. + + .. code-block:: python + + import torch + from transformers import AutoModelForCausalLM, AutoTokenizer + device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") + model_name = "NousResearch/Meta-Llama-3-8B" + + tokenizer = AutoTokenizer.from_pretrained(model_name, torch_dtype=torch.float16, use_fast=False) + inputs = tokenizer('Today is', return_tensors='pt').to(device) + + model_eager = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, attn_implementation="eager").cuda(device) + model_ckFAv2 = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda(device) + + print("eager GQA: ", tokenizer.decode(model_eager.generate(**inputs, max_new_tokens=10)[0], skip_special_tokens=True)) + print("ckFAv2 GQA: ", tokenizer.decode(model_ckFAv2.generate(**inputs, max_new_tokens=10)[0], skip_special_tokens=True)) + + # eager GQA: Today is the day of the Lord, and we are the + # ckFAv2 GQA: Today is the day of the Lord, and we are the + + .. tab-item:: Triton Flash Attention 2 + + The Triton Flash Attention 2 module is implemented in Python and uses OpenAI’s JIT compiler. This module has been + upstreamed into the vLLM serving toolkit, discussed in :doc:'llm-inference-frameworks'. + + 1. To install Triton Flash Attention 2 and run the benchmark, use the following commands. + + .. code-block:: shell + + # Install from the source + pip uninstall pytorch-triton-rocm triton -y + git clone https://github.com/ROCm/triton.git + cd triton/python + GPU_ARCHS=gfx942 python setup.py install #MI300 series + pip install matplotlib pandas + + 2. To test, run the Triton Flash Attention 2 performance benchmark. + + .. code-block:: shell + + # Test the triton FA v2 kernel + python https://github.com/ROCm/triton/blob/triton-mlir/python/perf-kernels/flash-attention.py + # Results (Okay to release TFLOPS number ???) + fused-attention-fwd-d128: + BATCH HQ HK N_CTX_Q N_CTX_K TFLOPS + 0 16.0 16.0 16.0 1024.0 1024.0 287.528411 + 1 8.0 16.0 16.0 2048.0 2048.0 287.490806 + 2 4.0 16.0 16.0 4096.0 4096.0 345.966031 + 3 2.0 16.0 16.0 8192.0 8192.0 361.369510 + 4 1.0 16.0 16.0 16384.0 16384.0 356.873720 + 5 2.0 48.0 48.0 1024.0 1024.0 216.916235 + 6 2.0 48.0 48.0 2048.0 1024.0 271.027578 + 7 2.0 48.0 48.0 4096.0 8192.0 337.367372 + 8 2.0 48.0 48.0 8192.0 4096.0 363.481649 + 9 2.0 48.0 48.0 16384.0 8192.0 375.013622 + 10 8.0 16.0 16.0 1989.0 15344.0 321.791333 + 11 4.0 16.0 16.0 4097.0 163.0 122.104888 + 12 2.0 16.0 16.0 8122.0 2159.0 337.060283 + 13 1.0 16.0 16.0 16281.0 7.0 5.234012 + 14 2.0 48.0 48.0 1021.0 1020.0 214.657425 + 15 2.0 48.0 48.0 2001.0 2048.0 314.429118 + 16 2.0 48.0 48.0 3996.0 9639.0 330.411368 + 17 2.0 48.0 48.0 8181.0 1021.0 324.614980 + +xFormers +======== + +xFormers also improves the performance of attention modules. Although xFormers attention performs very +similarly to Flash Attention 2 due to its tiling behavior of query, key, and value, it’s widely used for LLMs and +Stable Diffusion models with the Hugging Face Diffusers library. + +Installing CK xFormers +---------------------- + +Use the following commands to install CK xFormers. + +.. code-block:: shell + + # Install from source + git clone https://github.com/ROCm/xformers.git + cd xformers/ + git submodule update --init --recursive + PYTORCH_ROCM_ARCH=gfx942 python setup.py install #Instinct MI300-series + +PyTorch built-in acceleration +============================= + +`PyTorch compilation +mode `__ +synthesizes the model into a graph and then lowers it to prime +operators. These operators are compiled using TorchInductor, which uses +OpenAI Triton as a building block for GPU acceleration. One advantage of +PyTorch compilation mode is that its GPU kernels are written in Python, +making modifying and extending them easier. PyTorch compilation mode +often delivers higher performance, as model operations are fused before +runtime, which allows for easy deployment of high-performance kernels. + +PyTorch compilation +------------------- + +To utilize the PyTorch compilation mode, specific layers of the model +must be explicitly assigned as compilation targets. In the case of LLM, +where autoregressive token decoding generates dynamically changing +key/value sizes, limiting the key/value size to a static dimension, +``max_cache_length``, is necessary to utilize the performance benefits +of the PyTorch compilation. + +.. code-block:: python + + # Sample script to run LLM with the static key-value cache and pytorch compilation + from transformers import AutoModelForCausalLM, AutoTokenizer, StaticCache + import torch + from typing import Optional + import os + device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") + os.environ["TOKENIZERS_PARALLELISM"] = "false" + model_name = "NousResearch/Meta-Llama-3-8B" + prompts = [] + + for b in range(1): + prompts.append("New york city is where " + ) + + tokenizer = AutoTokenizer.from_pretrained(model_name) + model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16).to(device).eval() + inputs = tokenizer(prompts, return_tensors="pt").to(model.device) + + def decode_one_tokens(model, cur_token, input_pos, cache_position): + logits = model(cur_token, position_ids=input_pos, cache_position=cache_position, return_dict=False, use_cache=True)[0] + new_token = torch.argmax(logits[:, -1], dim=-1)[:, None] + return new_token + + batch_size, seq_length = inputs["input_ids"].shape + # static key-value cache + max_cache_length = 1024 + max_new_tokens = 10 + model._setup_cache(StaticCache, batch_size, max_cache_len=max_cache_length) + cache_position = torch.arange(seq_length, device=device) + generated_ids = torch.zeros(batch_size, seq_length + max_new_tokens + 1, dtype=torch.int, device=device) + generated_ids[:, cache_position] = inputs["input_ids"].to(device).to(torch.int) + + logits = model(**inputs, cache_position=cache_position, return_dict=False, use_cache=True)[0] + next_token = torch.argmax(logits[:, -1], dim=-1)[:, None] + # torch compilation + decode_one_tokens = torch.compile(decode_one_tokens, mode="max-autotune-no-cudagraphs",fullgraph=True) + + generated_ids[:, seq_length] = next_token[:, 0] + cache_position = torch.tensor([seq_length + 1], device=device) + + with torch.no_grad(): + for _ in range(1, max_new_tokens): + with torch.backends.cuda.sdp_kernel(enable_flash=False, enable_mem_efficient=False, enable_math=True): + next_token = decode_one_tokens(model, next_token.clone(), None, cache_position) + generated_ids[:, cache_position] = next_token.int() + cache_position += 1 + +.. _fine-tuning-llms-pytorch-tunableop: + +PyTorch TunableOp +------------------ + +ROCm PyTorch (2.2.0 and later) allows users to use high-performance ROCm +GEMM kernel libraries through PyTorch's built-in TunableOp options. +This enables users to automatically pick up the best-performing GEMM +kernels from :doc:`rocBLAS ` and :doc:`hipBLASLt ` libraries during runtime. + +During warm-up runs or offline profiling steps, users can create a GEMM Table +that enumerates the kernel information. During the model's run, the best-performing kernel substitutes +``torch.nn.functional.linear(input, weight, bias=None)`` with the kernel specified in the GEMM table. The +`Tunable GitHub `_ +page describes the options. + +.. code-block:: python + + # To turn on TunableOps, simply set this environmental variable + export PYTORCH_TUNABLEOP_ENABLED=1 + + # python + import torch + import torch.nn as nn + import torch.nn.functional as F + A = torch.rand(100, 20, device="cuda") + W = torch.rand(200, 20, device="cuda") + Out = F.linear(A, W) + print(Out.size()) + + # tunableop_results0.csv + Validator,PT_VERSION,2.4.0 + Validator,ROCM_VERSION,6.1.0.0-82-5fabb4c + Validator,HIPBLASLT_VERSION,0.7.0-1549b021 + Validator,GCN_ARCH_NAME,gfx942:sramecc+:xnack- + Validator,ROCBLAS_VERSION,4.1.0-cefa4a9b-dirty + GemmTunableOp_float_TN,tn_200_100_20,Gemm_Rocblas_32323,0.00669595 + +.. image:: ../../data/how-to/fine-tuning-llms/tunableop.png + :alt: GEMM and TunableOp + :align: center + +Learn more about optimizing kernels with TunableOp in +:ref:`Optimizing Triton kernels `. diff --git a/docs/how-to/fine-tuning-llms/model-quantization.rst b/docs/how-to/fine-tuning-llms/model-quantization.rst new file mode 100644 index 0000000000..18d604b3d4 --- /dev/null +++ b/docs/how-to/fine-tuning-llms/model-quantization.rst @@ -0,0 +1,257 @@ +.. meta:: + :description: How to fine-tune LLMs with ROCm + :keywords: ROCm, LLM, fine-tuning, usage, tutorial, quantization, GPTQ, transformers, bitsandbytes + +***************************** +Model quantization techniques +***************************** + +Quantization reduces the model size compared to its native full-precision version, making it easier to fit large models +onto accelerators or GPUs with limited memory usage. This section explains how to perform LLM quantization using GPTQ +and bitsandbytes on AMD Instinct hardware. + +.. _fine-tune-llms-gptq: + +GPTQ +==== + +GPTQ is a post-training quantization technique where each row of the weight matrix is quantized independently to find a +version of the weights that minimizes error. These weights are quantized to ``int4`` but are restored to ``fp16`` on the +fly during inference. This can save your memory usage by a factor of four. A speedup in inference is expected because +inference of GPTQ models uses a lower bit width, which takes less time to communicate. + +Before setting up the GPTQ configuration in Transformers, ensure the `AutoGPTQ `_ library +is installed. + +Installing AutoGPTQ +------------------- + +The AutoGPTQ library implements the GPTQ algorithm. + +#. Use the following command to install the latest stable release of AutoGPTQ from pip. + + .. code-block:: shell + + # This will install pre-built wheel for a specific ROCm version + + pip install auto-gptq --no-build-isolation --extra-index-url https://huggingface.github.io/autogptq-index/whl/rocm573/ + + Or, install AutoGPTQ from source for the appropriate ROCm version (for example, ROCm 6.1). + + .. code-block:: shell + + # Clone the source code + git clone https://github.com/AutoGPTQ/AutoGPTQ.git + cd AutoGPTQ + + # Speed up the compilation by specifying PYTORCH_ROCM_ARCH to target device + PYTORCH_ROCM_ARCH=gfx942 ROCM_VERSION=6.1 pip install . + + # Show the package after the installation + +#. Run ``pip show auto-gptq`` to print information for the installed ``auto-gptq`` package. Its output should look like + this: + + .. code-block:: shell + + Name: auto-gptq + Version: 0.8.0.dev0+rocm6.1 + ... + +Using GPTQ with AutoGPTQ +------------------------ + +#. Run the following code snippet. + + .. code-block:: python + + from transformers import AutoTokenizer, TextGenerationPipeline + from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig + base_model_name = "NousResearch/Llama-2-7b-hf" + quantized_model_name = "llama-2-7b-hf-gptq" + tokenizer = AutoTokenizer.from_pretrained(base_model_name, use_fast=True) + examples = [ + tokenizer( + "auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm." + ) + ] + print(examples) + + The resulting examples should be a list of dictionaries whose keys are ``input_ids`` and ``attention_mask``. + +#. Set up the quantization configuration using the following snippet. + + .. code-block:: python + + quantize_config = BaseQuantizeConfig( + bits=4, # quantize model to 4-bit + group_size=128, # it is recommended to set the value to 128 + desc_act=False, + ) + +#. Load the non-quantized model using the AutoGPTQ class and run the quantization. + + .. code-block:: python + + # import auto_gptq class + from auto_gptq import AutoGPTQForCausalLM + # load non-quantized model + base_model = AutoGPTQForCausalLM.from_pretrained(base_model_name, quantize_config, device_map = "auto") + base_model.quantize(examples) + # save quantized model + base_model.save_quantized(quantized_model_name) + +Using GPTQ with Hugging Face Transformers +------------------------------------------ + +#. To perform a GPTQ quantization using Hugging Face Transformers, you need to create a ``GPTQConfig`` instance and set the + number of bits to quantize to, and a dataset to calibrate the weights. + + .. code-block:: python + + from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig + + base_model_name = " NousResearch/Llama-2-7b-hf" + tokenizer = AutoTokenizer.from_pretrained(base_model_name) + gptq_config = GPTQConfig(bits=4, dataset="c4", tokenizer=tokenizer) + +#. Load a model to quantize using ``AutoModelForCausalLM`` and pass the + ``gptq_config`` to its ``from_pretained`` method. Set ``device_map=”auto”`` to + automatically offload the model to available GPU resources. + + .. code-block:: python + + quantized_model = AutoModelForCausalLM.from_pretrained( + base_model_name, + device_map="auto", + quantization_config=gptq_config) + +#. Once the model is quantized, you can push the model and tokenizer to Hugging Face Hub for easy share and access. + + .. code-block:: python + + quantized_model.push_to_hub("llama-2-7b-hf-gptq") + tokenizer.push_to_hub("llama-2-7b-hf-gptq") + + Or, you can save the model locally using the following snippet. + + .. code-block:: python + + quantized_model.save_pretrained("llama-2-7b-gptq") + tokenizer.save_pretrained("llama-2-7b-gptq") + +ExLlama-v2 support +------------------ + +ExLlama is a Python/C++/CUDA implementation of the Llama model that is +designed for faster inference with 4-bit GPTQ weights. The ExLlama +kernel is activated by default when users create a ``GPTQConfig`` object. To +boost inference speed even further on Instinct accelerators, use the ExLlama-v2 +kernels by configuring the ``exllama_config`` parameter as the following. + +.. code-block:: python + + from transformers import AutoModelForCausalLM, GPTQConfig + pretrained_model_dir = "meta-llama/Llama-2-7b" + gptq_config = GPTQConfig(bits=4, exllama_config={"version":2}) + quantized_model = AutoModelForCausalLM.from_pretrained( + base_model_name, + device_map="auto", + quantization_config=gptq_config) + +bitsandbytes +============ + +The `ROCm-aware bitsandbytes `_ library is +a lightweight Python wrapper around CUDA custom functions, in particular 8-bit optimizer, matrix multiplication, and +8-bit and 4-bit quantization functions. The library includes quantization primitives for 8-bit and 4-bit operations +through ``bitsandbytes.nn.Linear8bitLt`` and ``bitsandbytes.nn.Linear4bit`` and 8-bit optimizers through the +``bitsandbytes.optim`` module. These modules are supported on AMD Instinct accelerators. + +Installing bitsandbytes +----------------------- + +#. To install bitsandbytes for ROCm 6.0 (and later), use the following commands. + + .. code-block:: shell + + # Clone the github repo + git clone --recurse https://github.com/ROCm/bitsandbytes.git + cd bitsandbytes + git checkout rocm_enabled + + # Install dependencies + pip install -r requirements-dev.txt + + # Use -DBNB_ROCM_ARCH to specify target GPU arch + cmake -DBNB_ROCM_ARCH="gfx942" -DCOMPUTE_BACKEND=hip -S . + + # Install + python setup.py install + +#. Run ``pip show bitsandbytes`` to show the information about the installed bitsandbytes package. Its output should + look like the following. + + .. code-block:: shell + + Name: bitsandbytes + Version: 0.44.0.dev0 + ... + +Using bitsandbytes primitives +----------------------------- + +To get started with bitsandbytes primitives, use the following code a reference. + +.. code-block:: python + + import bitsandbytes as bnb + + # Use Int8 Matrix Multiplication + bnb.matmul(..., threshold=6.0) + + # Use bitsandbytes 8-bit Optimizers + adam = bnb.optim.Adam8bit(model.parameters(), lr=0.001, betas=(0.9, 0.995)) + +Using bitsandbytes with Hugging Face Transformers +------------------------------------------------- + +To load a Transformers model in 4-bit, set ``load_int_4bt=true`` in ``BitsAndBytesConfig``. + +.. code-block:: python + + from transformers import AutoModelForCausalLM + from bitsandbytes import BitsAndBytesConfig + + base_model_name = "NousResearch/Llama-2-7b-hf" + quantization_config = BitsAndBytesConfig(load_in_4bit=True) + bnb_model_4bit = AutoModelForCausalLM.from_pretrained( + base_model_name, + device_map="auto", + quantization_config=quantization_config) + + # check the memory footprint with get_memory_footprint method + print(bnb_model_4bit.get_memory_footprint()) + +To load a model in 8-bit for inference, use the ``load_in_8bit`` option. + +.. code-block:: python + + from transformers import AutoModelForCausalLM, AutoTokenizer + from bitsandbytes import BitsAndBytesConfig + + base_model_name = "NousResearch/Llama-2-7b-hf" + + tokenizer = AutoTokenizer.from_pretrained(base_model_name) + quantization_config = BitsAndBytesConfig(load_in_8bit=True) + tokenizer = AutoTokenizer.from_pretrained(base_model_name) + bnb_model_8bit = AutoModelForCausalLM.from_pretrained( + base_model_name, + device_map="auto", + quantization_config=quantization_config) + + prompt = "What is a large language model?" + inputs = tokenizer(prompt, return_tensors="pt").to("cuda") + generated_ids = model.generate(**inputs) + outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) + diff --git a/docs/how-to/fine-tuning-llms/multi-gpu-fine-tuning-and-inference.rst b/docs/how-to/fine-tuning-llms/multi-gpu-fine-tuning-and-inference.rst new file mode 100644 index 0000000000..b567c60cb1 --- /dev/null +++ b/docs/how-to/fine-tuning-llms/multi-gpu-fine-tuning-and-inference.rst @@ -0,0 +1,236 @@ +.. meta:: + :description: Model fine-tuning and inference on a multi-GPU system + :keywords: ROCm, LLM, fine-tuning, usage, tutorial, multi-GPU, distributed, inference + +***************************************************** +Fine-tuning and inference using multiple accelerators +***************************************************** + +This section explains how to fine-tune a model on a multi-accelerator system. See +:doc:`Single-accelerator fine-tuning ` for a single accelerator or GPU setup. + +.. _fine-tuning-llms-multi-gpu-env: + +Environment setup +================= + +This section was tested using the following hardware and software environment. + +.. list-table:: + :stub-columns: 1 + + * - Hardware + - 4 AMD Instinct MI300X accelerators + + * - Software + - ROCm 6.1, Ubuntu 22.04, PyTorch 2.1.2, Python 3.10 + + * - Libraries + - ``transformers`` ``datasets`` ``accelerate`` ``huggingface-hub`` ``peft`` ``trl`` ``scipy`` + + * - Base model + - ``meta-llama/Llama-2-7b-chat-hf`` + +.. _fine-tuning-llms-multi-gpu-env-setup: + +Setting up the base implementation environment +---------------------------------------------- + +#. Install PyTorch for ROCm. Refer to the + :doc:`PyTorch installation guide `. For consistent + installation, it’s recommended to use official ROCm prebuilt Docker images with the framework pre-installed. + +#. In the Docker container, check the availability of ROCM-capable accelerators using the following command. + + .. code-block:: shell + + rocm-smi -showproductname + +#. Check that your accelerators are available to PyTorch. + + .. code-block:: python + + import torch + print("Is a ROCm-GPU detected? ", torch.cuda.is_available()) + print("How many ROCm-GPUs are detected? ", torch.cuda.device_count()) + + If successful, your output should look like this: + + .. code-block:: shell + + >>> print("Is a ROCm-GPU detected? ", torch.cuda.is_available()) + Is a ROCm-GPU detected? True + >>> print("How many ROCm-GPUs are detected? ", torch.cuda.device_count()) + How many ROCm-GPUs are detected? 4 + +.. tip:: + + During training and inference, you can check the memory usage by running the ``rocm-smi`` command in your terminal. + This tool helps you see shows which accelerators or GPUs are involved. + + +.. _fine-tuning-llms-multi-gpu-hugging-face-accelerate: + +Hugging Face Accelerate for fine-tuning and inference +=========================================================== + +`Hugging Face Accelerate `_ is a library that simplifies turning raw +PyTorch code for a single accelerator into code for multiple accelerators for LLM fine-tuning and inference. It is +integrated with `Transformers `_ allowing you to scale your PyTorch +code while maintaining performance and flexibility. + +As a brief example of model fine-tuning and inference using multiple GPUs, let's use Transformers and load in the Llama +2 7B model. + +Here, let's reuse the code in :ref:`Single-accelerator fine-tuning ` +to load the base model and tokenizer. + +Now, it's important to adjust how you load the model. Add the ``device_map`` parameter to your base model configuration. + +.. code-block:: python + + ... + base_model_name = "meta-llama/Llama-2-7b-chat-hf" + + # Load base model to GPU memory + base_model = AutoModelForCausalLM.from_pretrained( + base_model_name, + device_map = "auto" + trust_remote_code = True) + ... + # Run training + sft_trainer.train() + +.. note:: + + You can let Accelerate handle the device map computation by setting ``device_map`` to one of the supported options + (``"auto"``, ``"balanced"``, ``"balanced_low_0"``, ``"sequential"``). + + It's recommended to set the ``device_map`` parameter to ``“auto”`` to allow Accelerate to automatically and + efficiently allocate the model given the available resources (4 accelerators in this case). + + When you have more GPU memory available than the model size, here is the difference between each ``device_map`` + option: + + * ``"auto"`` and ``"balanced"`` evenly split the model on all available GPUs, making it possible for you to use a + batch size greater than 1. + + * ``"balanced_low_0"`` evenly splits the model on all GPUs except the first + one, and only puts on GPU 0 what does not fit on the others. This + option is great when you need to use GPU 0 for some processing of the + outputs, like when using the generate function for Transformers + models. + + * ``"sequential"`` will fit what it can on GPU 0, then move on GPU 1 and so forth. Not all GPUs might be used. + +After loading the model in this way, the model is fully ready to use the resources available to it. + +.. _fine-tuning-llms-multi-gpu-torchtune: + +torchtune for fine-tuning and inference +============================================= + +torchtune is a PyTorch-native library for easy single and multi-accelerator or GPU model fine-tuning and inference with +LLMs. + +#. Install torchtune using pip. + + .. code-block:: shell + + # Install torchtune with PyTorch release 2.2.2+ + pip install torchtune + + # To confirm that the package is installed correctly + tune --help + + The output should look like this: + + .. code-block:: shell + + usage: tune [-h] {download,ls,cp,run,validate} ... + + Welcome to the TorchTune CLI! + + options: + -h, --help show this help message and exit + + subcommands: + {download,ls,cp,run,validate} + +torchtune recipes are designed around easily composable components and workable training loops, with minimal abstraction +getting in the way of fine-tuning. Run ``tune ls`` to show built-in torchtune configuration recipes. + +.. code-block:: shell + + RECIPE CONFIG + full_finetune_single_device llama2/7B_full_low_memory + llama3/8B_full_single_device + mistral/7B_full_low_memory + full_finetune_distributed llama2/7B_full + llama2/13B_full + llama3/8B_full + mistral/7B_full + gemma/2B_full + lora_finetune_single_device llama2/7B_lora_single_device + llama2/7B_qlora_single_device + llama3/8B_lora_single_device + llama3/8B_qlora_single_device + llama2/13B_qlora_single_device + mistral/7B_lora_single_device + +The ``RECIPE`` column shows the easy-to-use and workable fine-tuning and inference recipes for popular fine-tuning +techniques (such as LoRA). The ``CONFIG`` column lists the YAML configurations for easily configuring training, +evaluation, quantization, or inference recipes. + +The snippet shows the architecture of a model's YAML configuration file: + +.. code-block:: yaml + + # Model Arguments + model: + _component_: torchtune.models.llama2.lora_llama2_7b + lora_attn_modules: ['q_proj', 'v_proj'] + apply_lora_to_mlp: False + apply_lora_to_output: False + lora_rank: 8 + lora_alpha: 16 + + tokenizer: + _component_: torchtune.models.llama2.llama2_tokenizer + path: /tmp/Llama-2-7b-hf/tokenizer.model + + # Dataset and Sampler + dataset: + _component_: torchtune.datasets.alpaca_cleaned_dataset + train_on_input: True + +This configuration file defines the fine-tuning base model path, data set, hyper-parameters for optimizer and scheduler, +and training data type. To download the base model for fine-tuning, run the following command: + +.. code-block:: shell + + tune download meta-llama/Llama-2-7b-hf --output-dir /tmp/Llama-2-7b-hf --hf-token + +The output directory argument for ``--output-dir`` should map the model path specified in YAML config file. + +To launch ``lora_finetune_distributed`` on four devices, run the following +command: + +.. code-block:: shell + + tune run --nnodes 1 --nproc_per_node 4 lora_finetune_distributed --config llama2/7B_lora + +If successful, you should something like the following output: + +.. code-block:: shell + + INFO:torchtune.utils.logging:FSDP is enabled. Instantiating Model on CPU for Rank 0 ... + INFO:torchtune.utils.logging:Model instantiation took 7.32 secs + INFO:torchtune.utils.logging:Memory Stats after model init: + {'peak_memory_active': 9.478172672, 'peak_memory_alloc': 8.953868288, 'peak_memory_reserved': 11.112808448} + INFO:torchtune.utils.logging:Optimizer and loss are initialized. + INFO:torchtune.utils.logging:Dataset and Sampler are initialized. + INFO:torchtune.utils.logging:Learning rate scheduler is initialized. + 1|111|Loss: 1.5790324211120605: 7%|█ | 114/1618 + +Read more about inference frameworks in :doc:`LLM inference frameworks `. diff --git a/docs/how-to/fine-tuning-llms/optimizing-triton-kernel.rst b/docs/how-to/fine-tuning-llms/optimizing-triton-kernel.rst new file mode 100644 index 0000000000..cac5493dc5 --- /dev/null +++ b/docs/how-to/fine-tuning-llms/optimizing-triton-kernel.rst @@ -0,0 +1,388 @@ +.. meta:: + :description: How to fine-tune LLMs with ROCm + :keywords: ROCm, LLM, fine-tuning, usage, tutorial, Triton, kernel, performance, optimization + +************************* +Optimizing Triton kernels +************************* + +This section introduces the general steps for `Triton `_ kernel optimization. Broadly, +Triton kernel optimization is similar to HIP and CUDA kernel optimization. + +.. _fine-tuning-llms-triton-memory-access-efficiency: + +Memory access efficiency +======================== + +The accelerator or GPU contains global memory, local data share (LDS), and registers. Global memory has high access +latency, but is large. LDS access has much lower latency, but is smaller. Register access is the fastest yet smallest +among the three. + +So, the data in global memory should be loaded and stored as few times as possible. If different threads in a block +need to access the same data, these data should be first transferred from global memory to LDS, then accessed by +different threads in a workgroup. + +.. _fine-tuning-llms-triton-hardware-resource-utilization: + +Hardware resource utilization +============================= + +Each accelerator or GPU has multiple Compute Units (CUs) and various CUs do computation in parallel. So, how many CUs +can a compute kernel can allocate its task to? For the :doc:`AMD MI300X accelerator <../../reference/gpu-arch-specs>`, the +grid should have at least 1024 thread blocks or workgroups. + +.. figure:: ../../data/how-to/fine-tuning-llms/compute-unit.png + + Schematic representation of a CU in the CDNA2 or CDNA3 architecture. + +To increase hardware utilization and maximize parallelism, it is necessary to design algorithms that can exploit more +parallelism. One approach to achieving this is by using larger split-K techniques for General Matrix Multiply (GEMM) +operations, which can further distribute the computation across more CUs, thereby enhancing performance. + +.. tip:: + + You can query hardware resources with the command ``rocminfo`` (in the ``/opt/rocm/bin`` directory). For instance, + query the number of CUs, number of SIMD, and wavefront size using the following commands. + + .. code-block:: shell + + rocminfo | grep "Compute Unit" + + rocminfo | grep "SIMD" + + rocminfo | grep "Wavefront Size" + + On an MI300X device, there are 304 CUs, 4 SIMD per CU, and the wavefront size (warp size) is 64. See :doc:`Hardware + specifications <../../reference/gpu-arch-specs>` for a full list of AMD accelerators and GPUs. + +.. _fine-tuning-llms-triton-ir-analysis: + +IR analysis +=========== + +In Triton, there are several layouts including *blocked*, *shared*, *sliced*, and *MFMA*. + +From the Triton GPU IR (intermediate representation), you can know in which memory each computation is +performed. The following is a snippet of IR from the Flash Attention decode ``int4`` key-value program. It is to +de-quantize the ``int4`` key-value from the ``int4`` data type to ``fp16``. + +.. code-block:: + + %190 = tt.load %189 {cache = 1 : i32, evict = 1 : i32, isVolatile = + false} : tensor<1x64xi32, #blocked6> loc(#loc159) + + %266 = arith.andi %190, %cst_28 : tensor<1x64xi32, #blocked6> + loc(#loc250) + + %267 = arith.trunci %266 : tensor<1x64xi32, #blocked6> to + tensor<1x64xi16, #blocked6> loc(#loc251) + + %268 = tt.bitcast %267 : tensor<1x64xi16, #blocked6> -> tensor<1x64xf16, + #blocked6> loc(#loc252) + + %269 = triton_gpu.convert_layout %268 : (tensor<1x64xf16, #blocked6>) -> + tensor<1x64xf16, #shared1> loc(#loc252) + + %270 = tt.trans %269 : (tensor<1x64xf16, #shared1>) -> tensor<64x1xf16, + #shared2> loc(#loc194) + + %276 = triton_gpu.convert_layout %270 : (tensor<64x1xf16, #shared2>) -> + tensor<64x1xf16, #blocked5> loc(#loc254) + + %293 = arith.mulf %276, %cst_30 : tensor<64x1xf16, #blocked5> + loc(#loc254) + + %295 = arith.mulf %292, %294 : tensor<64x32xf16, #blocked5> loc(#loc264) + + %297 = arith.addf %295, %296 : tensor<64x32xf16, #blocked5> loc(#loc255) + + %298 = triton_gpu.convert_layout %297 : (tensor<64x32xf16, #blocked5>) + -> tensor<64x32xf16, #shared1> loc(#loc255) + + %299 = tt.trans %298 : (tensor<64x32xf16, #shared1>) -> + tensor<32x64xf16, #shared2> loc(#loc196) + + %300 = triton_gpu.convert_layout %299 : (tensor<32x64xf16, #shared2>) -> + tensor<32x64xf16, #triton_gpu.dot_op<{opIdx = 1, parent = #mfma, kWidth + = 4}>> loc(#loc197) + +From the IR, you can see ``i32`` data is loaded from global memory to registers. With a few element-wise operations in +registers, then it is stored in shared memory for the transpose operation, which needs data movement across different +threads. With the transpose done, it is loaded from LDS to register again, and with a few more element-wise operations, +they are stored in LDS again. The last step is to load from LDS to registers and convert to the dot-operand layout. + +From the IR, you can see that it uses the LDS twice: one for the transpose, and the other to convert the blocked layout +to a dot-operand layout. + +Assembly analysis +================= + +In the ISA, ensure ``global_load_dwordx4`` is used, especially when the +load happens in a loop. + +In most cases, the LDS load and store should use ``_b128`` as well to +minimize the number of LDS access instructions. Note that upstream (or backend) might not have ``_b128`` LDS read/write, +so it uses ``_b64``. For most cases, no matter if you use fork or upstream, +the LDS access should have ``_b64`` vector width. + +The AMD ISA has the ``s_waitcnt`` instruction to synchronize the dependency +of memory access and computations. The ``s_waitcnt`` instruction can +have two signals, typically in the context of Triton: + +* ``lgkmcnt(n):`` `lgkm` stands for LDS, GDS, Constant and Message. + + In this context, it is often related to LDS access. The number ``n`` here means the number of such accesses that can + be left out to continue. For example, 0 means all ``lgkm`` access must finish before continuing, and 1 means only 1 + ``lgkm`` access can be still running asynchronously before proceeding. + +* ``vmcnt(n):`` `vm` means vector memory. + + This happens when vector memory is accessed, for example, when global load moves from global memory to vector memory. + Again, the number ``n`` here means the number of accesses that can be left out to continue. + +Generally recommended guidelines are as follows. + +* Vectorize memory access as much as possible. + +* Ensure synchronization is done efficiently. + +* Overlap of instructions to hide latency, but it requires thoughtful + analysis of the algorithms. + +* If you find inefficiencies, you can trace it back to LLVM IR, TTGIR + and even TTIR to see where the problem comes from. If you find it + during compiler optimization, activate the MLIR dump and check which + optimization pass caused the problem. + +.. _fine-tuning-llms-triton-kernel-occupancy: + +Kernel occupancy +================ + +1. Get the VGPR count, search for ``.vgpr_count`` in the ISA (for example, ``N``). + +2. Get the allocated LDS following the steps (for example, L for the kernel). + + a. ``export MLIR_ENABLE_DUMP=1`` + + b. ``rm -rf ~/.triton/cache`` + + c. ``python kernel.py | | grep "triton_gpu.shared = " | tail -n 1`` + + d. You should see something like ``triton_gpu.shared = 65536``, indicating 65536 bytes of LDS are allocated for the + kernel. + +3. Get number of waves per workgroup using the following steps (for example, ``nW``). + + a. ``export MLIR_ENABLE_DUMP=1`` + + b. ``rm -rf ~/.triton/cache`` + + c. ``python kernel.py | | grep "triton_gpu.num-warps " | tail -n 1`` + + d. You should see something like ``“triton_gpu.num-warps" = 8``, indicating 8 waves per workgroup. + +4. Compute occupancy limited by VGPR based on N according to the following table. For example, waves per EU as + ``occ_vgpr``. + +.. _fine-tuning-llms-occupancy-vgpr-table: + +.. figure:: ../../data/how-to/fine-tuning-llms/occupancy-vgpr.png + :alt: Occupancy related to VGPR usage in an Instinct MI300X accelerator. + :align: center + +5. Compute occupancy limited by LDS based on L by: ``occ_lds = floor(65536 / L)``. + +6. Then the occupancy is ``occ = min(floor(occ_vgpr * 4 / nW), occ_lds) * nW / 4`` + + a. ``occ_vgpr \* 4`` gives the total number of waves on all 4 execution units (SIMDs) + per CU. + + b. ``floor(occ_vgpr * 4 / nW)`` gives the occupancy of workgroups per CU + regrading VGPR usage. + + c. The true ``occ`` is the minimum of the two. + +.. _fine-tuning-llms-triton-kernel-configs-env-vars: + +Auto-tunable kernel configurations and environment variables +============================================================ + +This section relates to the amount of :ref:`memory access ` and +computation assigned to each CU. It is related to the usage of LDS, registers and the scheduling of different tasks on +a CU. + +The following is a list of kernel arguments used for tuning. + +``num_stages=n`` + Adjusts the number of pipeline stages for different types of kernels. On AMD accelerators, set ``num_stages`` + according to the following rules: + + * For kernels with a single GEMM, set to ``0``. + + * For kernels with two GEMMs fused (Flash Attention, or any other kernel + that fuses 2 GEMMs), set to ``1``. + + * For kernels that fuse a single GEMM with another non-GEMM operator + (for example ReLU activation), set to ``0``. + + * For kernels that have no GEMMs, set to ``1``. + +``waves_per_eu=n`` + Helps to manage Vector General Purpose Registers (VGPR) usage to achieve desired occupancy levels. This argument + hints to the compiler to reduce VGPR to achieve ``n`` occupancy. See + :ref:`Kernel occupancy ` for more information about how to compute + occupancy. + + This argument is useful if: + + * The occupancy of the kernel is limited by VGPR usage. + + * The current VGPR usage is only a few above a boundary in + :ref:`Occupancy related to VGPR usage in an Instinct MI300X accelerator `. + + For example, according to the table, the available VGPR is 512 per Execution Unit (EU), and VGPU is allocated at the + unit of 16. If the current VGPR usage is 170, the actual requested VGPR will be 176, so the + occupancy is only 2 waves per CU since :math:`176 \times 3 > 512`. So, if you set + ``waves_per_eu`` to 3, the LLVM backend tries to bring VGPR usage down so + that it might fit 3 waves per EU. + +``BLOCK_M``, ``BLOCK_N``, ``BLOCK_K`` + Tile sizes to be tuned to balance the memory-to-computation ratio. You want tile sizes large enough to + maximize the efficiency of memory-to-computation ratio, but small enough to parallelize the greatest number of + workgroups at the grid level. + +``matrix_instr_nonkdim`` + Experimental feature for Flash Attention-like kernels that determines the size of the Matrix Fused Multiply-Add + (MFMA) instruction used. + + - ``Matrix_instr_nonkdim = 16``: ``mfma_16x16`` is used. + + - ``Matrix_instr_nonkdim = 32``: ``mfma_32x32`` is used. + + For GEMM kernels on an AMD MI300X accelerator, ``mfma_16x16`` typically outperforms ``mfma_32x32``, even for large + tile/GEMM sizes. + +The following is an environment variable used for tuning. + +``OPTIMIZE_EPILOGUE`` + Setting this variable to ``1`` can improve performance by removing the ``convert_layout`` operation in the epilogue. + It should be turned on (set to ``1``) in most cases. Setting ``OPTIMIZE_EPILOGUE=1`` stores the MFMA instruction + results in the MFMA layout directly; this comes at the cost of reduced global store efficiency, but the impact on + kernel execution time is usually minimal. + + By default (``0``), the results of MFMA instruction are converted to blocked layout, which leads to ``global_store`` + with maximum vector length, that is ``global_store_dwordx4``. + + This is done implicitly with LDS as the intermediate buffer to achieve + data exchange between threads. Padding is used in LDS to avoid bank + conflicts. This usually leads to extra LDS usage, which might reduce + occupancy. + + .. note:: + + This variable is not turned on by default because it only + works with ``tt.store`` but not ``tt.atomic_add``, which is used in split-k and + stream-k GEMM kernels. In the future, it might be enabled with + ``tt.atomic_add`` and turned on by default. + + See :ref:`IR analysis `. + +TorchInductor with Triton tuning knobs +=========================================== + +The following are suggestions for optimizing matrix multiplication (GEMM) and convolution (``conv``) operations in PyTorch +using ``inductor``, a part of the PyTorch compilation framework. The goal is to leverage Triton to achieve better +performance. + +Learn more about TorchInductor environment variables and usage in +`PyTorch documentation `_. + +To enable a ``gemm``/``conv`` lowering to Triton, it requires use of ``inductor``’s ``max_autotune`` mode. This benchmarks a +static list of Triton configurations (``conv`` configurations for max auto-tune + ``matmul`` configurations for max +auto-tune) and uses the fastest for each shape. Note that the Triton is not used if regular :doc:`MIOpen ` +or :doc:`rocBLAS ` is faster for a specific operation. + +* Set ``torch._inductor.config.max_autotune = True`` or ``TORCHINDUCTOR_MAX_AUTOTUNE=1``. + +* Or, for more fine-grained control: + + ``torch._inductor.config.max_autotune.pointwise = True`` + To enable tuning for ``pointwise``/``reduction`` ops. + + ``torch._inductor.config.max_autotune_gemm = True`` + To enable tuning or lowering of ``mm``/``conv``\s. + + ``torch._inductor.max_autotune_gemm_backends/TORCHINDUCTOR_MAX_AUTOTUNE_GEMM_BACKENDS`` + To select the candidate backends for ``mm`` auto-tuning. Defaults to + ``TRITON,ATEN,NV``. This also includes the ``CUTLASS`` tuning option. Limiting this to + ``TRITON`` might improve performance by enabling more fused ``mm`` kernels + instead of going to rocBLAS. + +* For ``mm`` tuning, tuning ``coordinate_descent`` might improve performance. + + ``torch._inductor.config.coordinate_descent_tuning = True`` or ``TORCHINDUCTOR_COORDINATE_DESCENT_TUNING=1`` + +* Inference can see large improvements on AMD GPUs by utilizing + ``torch._inductor.config.freezing=True`` or the ``TORCHINDUCTOR_FREEZING=1`` variable, which + in-lines weights as constants and enables constant folding optimizations. + +* Enabling ``inductor``’s cpp_wrapper might improve overhead. This generates + C++ code which launches Triton binaries directly with + ``hipModuleLaunchKernel`` and relies on `hipification`. + +* For NHWC convolutions workloads + ``torch._inductor.config.layout_optimization=True`` or ``TORCHINDUCTOR_LAYOUT_OPTIMIZATION=`` + can help be enforcing channels_last format throughout the graph avoiding + any additional transposes added by ``inductor``. Note that + ``PYTORCH_MIOPEN_SUGGEST_NHWC=1`` is recommended if using this. + +* Extracting the Triton kernel ``TORCH_COMPILE_DEBUG`` creates a + ``torch_compile_debug/`` directory at current path, in the ``output_code.py`` + the code-strings for the Triton kernels that are defined. Manual work is + then required to strip out the kernel and create kernel + compilation and launch via Triton. + +* For advanced ``matmul`` or ``conv`` configuration tuning, the ``inductor-gemm-tuner`` can + help. This implements the Triton ``conv``/``mm`` implementations used upstream + and allows specification of inputs and configuration tuning search space if new + tunings are found that can be added to the auto-tune list. + +Other guidelines +================ + +* Performance-critical HIP provides an environment variable, ``export HIP_FORCE_DEV_KERNARG=1``, + that can put HIP kernel arguments directly to + device memory to reduce the latency of accessing kernel arguments. It + can reduce 2 to 3 μs for some kernels. Setting this variable for the FA + decode containing ``splitK`` and reduced kernels can reduce the total time + by around 6 μs in the benchmark test. + +* Set the clock to deterministic. Use the command ``rocm-smi --setperfdeterminism 1900`` to set the max clock speed to + 1900MHz instead of the default 2100MHz. This can reduce the chance of clock speed decrease due to chip high temperature + by setting a lower cap. You can restore this setting to its default value with ``rocm-smi -r``. + +* Set Non-Uniform Memory Access (NUMA) auto-balance. Run the command ``cat /proc/sys/kernel/numa_balancing`` to check the + current setting. An output of ``0`` indicates this setting is available. If output is ``1``, run the command + ``sudo sh -c \\'echo 0 > /proc/sys/kernel/numa_balancing`` to set this. + +For these settings, the ``env_check.sh`` script automates the setting, resetting, and checking of the such +environments. Find the script at ``__. + +.. _fine-tuning-llms-triton-tunableop: + +TunableOp +--------- +`TunableOp `_ +is a feature used to define and optimize kernels that can have tunable parameters. This is useful in +optimizing the performance of custom kernels by exploring different parameter configurations to find the most efficient +setup. See more about PyTorch TunableOp :ref:`Model acceleration libraries `. + +You can easily manipulate the behavior TunableOp through environment variables, though you could use the C++ interface +``at::cuda::tunable::getTuningContext()``. A Python interface to the ``TuningContext`` does not yet exist. + +The default value is ``0``, which means only 1 iteration is attempted. Remember: there’s an overhead to tuning. To try +and minimize the overhead, only a limited number of iterations of a given operation are attempted. If you set this to +``10``, each solution for a given operation can run as many iterations as possible within 10ms. There is a hard-coded +upper limit of 100 iterations attempted per solution. This is a tuning parameter; if you want the tunings to be chosen +based on an average over multiple iterations, increase the allowed tuning duration. diff --git a/docs/how-to/fine-tuning-llms/optimizing-with-composable-kernel.md b/docs/how-to/fine-tuning-llms/optimizing-with-composable-kernel.md new file mode 100644 index 0000000000..6196f9d761 --- /dev/null +++ b/docs/how-to/fine-tuning-llms/optimizing-with-composable-kernel.md @@ -0,0 +1,484 @@ + + + + + + +# Optimizing with Composable Kernel + +The AMD ROCm™ Composable Kernel (CK) library provides a programming model for writing performance-critical kernels for machine learning workloads. It generates a general-purpose kernel during the compilation phase through a C++ template, enabling developers to achieve operation fusions on different data precisions. + +This article gives a high-level overview of CK General Matrix Multiplication (GEMM) kernel based on the design example of `03_gemm_bias_relu`. It also outlines the steps to construct the kernel and run it. Moreover, the article provides a detailed implementation of running SmoothQuant quantized INT8 models on AMD Instinct MI300X accelerators using CK. + +## High-level overview: a CK GEMM instance + +GEMM is a fundamental block in linear algebra, machine learning, and deep neural networks. It is defined as the operation: +{math}`E = α \times (A \times B) + β \times (D)`, with A and B as matrix inputs, α and β as scalar inputs, and D as a pre-existing matrix. +Take the commonly used linear transformation in a fully connected layer as an example. These terms correspond to input activation (A), weight (B), bias (D), and output (E), respectively. The example employs a `DeviceGemmMultipleD_Xdl_CShuffle` struct from CK library as the fundamental instance to explore the compute capability of AMD Instinct accelerators for the computation of GEMM. The implementation of the instance contains two phases: + +- [Template parameter definition](#template-parameter-definition) +- [Instantiating and running the templated kernel](#instantiating-and-running-the-templated-kernel) + +### Template parameter definition + +The template parameters of the instance are grouped into four parameter types: + +- [Parameters for determining matrix data precision](matrix-data-precision) +- [Parameters for determining matrix data layout](matrix-data-layout) +- [Parameters for determining extra operations on matrix elements](matrix-element-operation) +- [Performance-oriented tunable parameters](tunable-parameters) + + +```{figure} ../../data/how-to/fine-tuning-llms/ck-template_parameters.jpg +The template parameters of the selected GEMM kernel are classified into four groups. These template parameter groups should be defined properly before running the instance. +``` + +(matrix-data-precision)= + +#### Matrix data precision + +A, B, D, and E are defined as half-precision floating-point datatypes. The multiply-add results of matrix A and B are added with a pre-existing matrix D (half-precision), and the final GEMM results are also half-precision floating-points. + +```c++ +using ADataType = F16; +using BDataType = F16; +using AccDataType = F32; +using CShuffleDataType = F16; +using DDataType = F16; +using EDataType = F16; +``` + +`ADataType` and `BDataType` denote the data precision of the A and B input matrices. `AccDataType` determines the data precision used for representing the multiply-add results of A and B elements. These results are stored in a `CShuffle` module in local data share (LDS), a low-latency and high-bandwidth explicitly-addressed memory used for synchronization within a workgroup LDS for later use. + +`CShuffleDataType` denotes the data precision of `CShuffle` in LDS. + +`DDataType` denotes the data precision of the pre-existing D matrix stored in GPU global memory, while `EDatatype` denotes the data precision of the final output. The CK kernel supports a fusion strategy so that `CShuffle` can be added with a single pre-existing matrix in the same GPU kernel for better performance. + +(matrix-data-layout)= + +#### Matrix data layout + +```c++ +using ALayout = Row; +using BLayout = Col; +using DLayout = Row; +using ELayout = Row; +``` + +Following the convention of various linear algebra libraries, CK assumes that the input matrix A is an M x K matrix, meaning the matrix has M rows and K columns. Similarly, matrix B is assumed to be K x N, meaning it has K rows and N columns. In computing, row-major order and column-major order are commonly used ways to store matrices in linear storage. After understanding the matrix storage pattern, the underlying optimized memory access manner can be applied to achieve better performance depending on the storage ordering of these matrices. + +(matrix-element-operation)= + +#### Matrix element operation + +```c++ +using AElementOp = PassThrough; +using BElementOp = PassThrough; +using CDEElementOp = AddRelu; +``` + +CK supports the pre-processing of the matrix before calculating GEMM, that is, `C = AElementOp(A) * BElementOp(B)`. It similarly supports the post-processing of GEMM results the same way, that is, `E = CDEElementOp(C, D)`. + +`AElementOp` and `BElementOp` determine the operation applied to matrix A and B separately before GEMM, which is achieved by binding the operation with a C++ struct function. + +The above `PassThrough` denotes no operations are performed on the target matrix. `CDEELementOp` determines the operations applied to `CShuffle` output and matrix D. The following binding struct `AddRelu` shows an example of adding the `CShuffle` output and matrix D, and ReLU (Rectified Linear Unit) operations to the addition result. It then passes the results to matrix E. + +```c++ +struct AddRelu +{ + __host__ __device__ void operator()(ck::half_t& e, const ck::half_t& c, const ck::half_t& d) const + { + const ck::half_t x = c + d; + e = x > 0 ? x : 0; + } +}; +``` + +(tunable-parameters)= + +#### Tunable parameters + +The CK instance includes a series of tunable template parameters to control the parallel granularity of the workload to achieve load balancing on different hardware platforms. + +These parameters include Block Size, M/N/K Per Block, M/N per XDL, AK1, BK1, etc. + +- Block Size determines the number of threads in the thread block. +- M/N/K Per Block determines the size of tile that each thread block is responsible for calculating. +- M/N Per XDL refers to M/N size for Instinct accelerator Matrix Fused Multiply Add (MFMA) instructions operating on a per-wavefront basis. +- A/B K1 is related to the data type. It can be any value ranging from 1 to K Per Block. To achieve the optimal load/store performance, 128bit per load is suggested. In addition, the A/B loading parameters must be changed accordingly to match the A/B K1 value; otherwise, it will result in compilation errors. + +Conditions for achieving computational load balancing on different hardware platforms can vary. + +### Instantiating and running the templated kernel + +After determining the template parameters, we instantiate the kernel with actual arguments. Do one of the following: + +- Use `GetDeviceBuffer` from CK’s custom struct `DeviceMem` to pass the element values of the matrices that need to be calculated. +- Allocate device buffer via `hipMalloc`. Ensure the device buffer size can fit the matrix size. +- Pass matrix elements through the `data_ptr` method in the `Tensor` object if the matrix to be calculated is of `Tensor` type. + +The row and column, and stride information of input matrices are also passed to the instance. For batched GEMM, you must pass in additional batch count and batch stride values. The extra operations for pre and post-processing are also passed with an actual argument; for example, α and β for GEMM scaling operations. Afterward, the instantiated kernel is launched by the invoker, as illustrated in Figure 3. + + +```{figure} ../../data/how-to/fine-tuning-llms/ck-kernel_launch.jpg +Templated kernel launching consists of kernel instantiation, making arguments by passing in actual application parameters, creating an invoker, and running the instance through the invoker. +``` + +## Developing fused INT8 kernels for SmoothQuant models + +[SmoothQuant](https://github.com/mit-han-lab/smoothquant) (SQ) is a quantization algorithm that enables an INT8 quantization of both weights and activations for all the matrix multiplications in LLM. The required GPU kernel functionalities used to accelerate the inference of SQ models on Instinct accelerators are shown in the following table. + +:::{table} Functionalities used to implement SmoothQuant model inference. + +| Functionality descriptions | Corresponding wrappers | +|:-------------------------------------|-----------------------------------------| +| {math}`E = α \times (A \times B) + β \times (D)`, where A, B, D, E are INT8 2-D tensors; | E = Linear_ABDE_I8(A, B, D, {math}`\alpha`, {math}`\beta`) | +| {math}`E = RELU (α \times (A \times B) + β \times (D))`, where A, B, D, E are INT8 2-D tensors; | E = Linear_ReLU_ABDE_I8(A, B, D, {math}`\alpha`, {math}`\beta`) | +| {math}`E = α \times (A \times B) + β \times (D)`, where A, B are INT8 2-D tensors, D and E are FP32 2-D tensors; | E = Linear_AB_I8_DE_F32(A, B, D, {math}`\alpha`, {math}`\beta`) | +| {math}`E = α \times (A \times B)`, where A, B, E are INT8 3-D tensors; | E = BMM_ABE_I8(A, B, {math}`\alpha`) | +| {math}`E = α \times (A \times B)`, where A, B are INT8 3-D tensors, E is FP32 3-D tensor; | E = BMM_AB_I8_E_F32(A, B, {math}`\alpha`) | +::: + +### Operation flow analysis + +The following section discusses the analysis of the operation flow of `Linear_ReLU_ABDE_I8`. The rest of the wrappers in Table 1 can be analyzed similarly. + +The first operation in the process is to perform the multiplication of input matrices A and B. The resulting matrix C is then scaled with α to obtain T1. At the same time, the process performs a scaling operation on D elements to obtain T2. Afterward, the process performs matrix addition between T1 and T2, element activation calculation using ReLU, and element rounding sequentially. The operations to generate E1, E2, and E are encapsulated and completed by a user-defined template function in CK (given in the next sub-section). This template function is integrated into the fundamental instance directly during the compilation phase so that all these steps can be fused in a single GPU kernel. + + +```{figure} ../../data/how-to/fine-tuning-llms/ck-operation_flow.jpg +Operation flow. +``` + +The CK library contains many fundamental instances that implement different functions. Familiarize yourself with the names of various CK instances and determine whether they meet the target functional requirements. + +Second, consider whether the format of input data meets your actual calculation needs. For SQ models, the 8-bit integer data format (INT8) is applied for matrix calculations. + +Third, consider the platform for implementing CK instances. The instances suffixed with `xdl` only run on AMD Instinct accelerators after being compiled and cannot run on Radeon-series GPUs. This is due to the underlying device-specific instruction sets for implementing these basic instances. + +Here, we use [DeviceBatchedGemmMultiD_Xdl](https://github.com/ROCm/composable_kernel/tree/develop/example/24_batched_gemm) as the fundamental instance to implement the functionalities in the previous table. + + +```{figure} ../../data/how-to/fine-tuning-llms/ck-root_instance.jpg +Use the ‘DeviceBatchedGemmMultiD_Xdl’ instance as a root. +``` + +The `DeviceBatchedGemmMultiD_Xdl` instance realizes the batched GEMM `BMM_ABE_I8` and `BMM_AB_I8_E_F32` kernels directly by using the proper input and output data precision types. + +Based on the two batched GEMM kernels, GEMM kernel `Linear_ABDE_I8` and `Linear_AB_I8_DE_F32` can be implemented by expanding their input 2-D tensors to 3-D tensors. Then, the 3-D output tensors produced by the root instance are squeezed back to 2-D output tensors before returning back. + +For example, unsqueeze A (M, K) to A (1, M, K) before assigning it into the root instance and squeeze E (1, M, N) to (M, N) after the calculations of the root instance return back. `Linear_ReLU_ABDE_I8` is implemented by adding a ReLU operation on the result output of `Linear_ABDE_I8`. + +### Developing the complete function + +The inference of SQ quantized models relies on using PyTorch and Transformer libraries, and a tensor type is used to represent matrices and vectors in `torch`, the C++ data types in CK need to be replaced with the `torch::tensor` type. The data types of the input and output matrices should be a `tensor` type. + +In GEMM, the A and B inputs are two-dimensional matrices, and the required input matrices of the selected fundamental CK instance are three-dimensional matrices. Therefore, we must convert the input 2-D tensors to 3-D tensors, by using `tensor`'s `unsqueeze()` method before passing these matrices to the instance. For batched GEMM in the preceding table, ignore this step. + +```c++ +// Function input and output +torch::Tensor linear_relu_abde_i8( + torch::Tensor A_, + torch::Tensor B_, + torch::Tensor D_, + float alpha, + float beta) +{ + // Convert torch::Tensor A_ (M, K) to torch::Tensor A (1, M, K) + auto A = A_.unsqueeze(0); + + // Convert torch::Tensor B_ (K, N) to torch::Tensor A (1, K, N) + auto B = B_.unsqueeze(0); +... +``` + +As shown in the following code block, we obtain M, N, and K values using input tensor size values. This stride size information is used to reshape the input vector D and allocate the storage space of tensor E. Stride reflects the exact size of continuous elements in memory, which are passed as important parameters to the fundamental instance for GPU kernel use. + +```c++ + // Return the batch count from the size of dimension 0 + int batch_count = A.size(0); + + // Return the M, N, K from the size of dimension 1 & 2 + int M = A.size(1); + int N = B.size(1); + int K = A.size(2); + + // Initialize the stride size for A, B, D and E + int stride_A = K; + int stride_B = K; + int stride_D0 = N; + int stride_E = N; + + // Initialize the stride size for batched A, B, D and E + long long int batch_stride_A = M * K; + long long int batch_stride_B = K * N; + long long int batch_stride_D0 = M * N; + long long int batch_stride_E = M * N; + + // Convert the tensor of 2-D to 3-D + auto D = D_.view({1,-1}).repeat({M, 1}); + + // Allocate memory for E + auto E = torch::empty({batch_count, M, N}, + torch::dtype(torch::kInt8).device(A.device())); +``` + +In the following code block, `ADataType`, `BDataType` and `D0DataType` are used to denote the data precision of the input tensors A, B and D, respectively. `EDataType` is used to denote the data precision of output tensor E. These parameters are specified to `I8` data format (8-bit integer data format) to meet the kernel's design requirements. + +`AccDataType` determines the data precision used to represent the multiply-add results of A and B elements. Generally, a larger range data type is applied to store the multiply-add results of A and B to avoid result overflow; `I32` is applied in this case. The `CShuffleDataType I32` data type indicates that the multiply-add results continue to be stored in LDS as an `I32` data format. All of this is implemented through the following code block. + +```c++ + // Data precision + using ADataType = I8; + using BDataType = I8; + using AccDataType = I32; + using CShuffleDataType = I32; + using D0DataType = I8; + using DsDataType = ck::Tuple; + using EDataType = I8; +``` + +Following the convention of various linear algebra libraries, row-major and column-major orders are used to denote the ways of storing matrices in linear storage. The advantage of specifying matrix B as column major is that all the relevant matrix elements are stored continuously in GPU global memory when a row in A is multiplied by a column in B, which can help GPU achieve data consistency access to improve access performance. + +```c++ + // Specify tensor order + using ALayout = RowMajor; + using BLayout = ColumnMajor; + using D0Layout = RowMajor; + using DsLayout = ck::Tuple; + using ELayout = RowMajor; +``` + +In CK, `PassThrough` is a struct denoting if an operation is applied to the tensor it binds to. To fuse the operations between E1, E2, and E introduced in section [Operation flow analysis](#operation-flow-analysis), we define a custom C++ struct, `ScaleScaleAddRelu`, and bind it to `CDEELementOp`. It determines the operations that will be applied to `CShuffle` (A×B results), tensor D, α, and β. + +```c++ + // No operations bound to the elements of A and B + using AElementOp = PassThrough; + using BElementOp = PassThrough; + + // Operations bound to the elements of C, D and E + using CDEElementOp = ScaleScaleAddRelu; +``` + +In the binding struct, `operator()` performs an addition operation between `CShuffle` and matrix D, a ReLU operation on the addition results, and a rounding operation on the output elements. It then returns the results to E. + +```c++ +struct ScaleScaleAddRelu { + + template <> + __host__ __device__ constexpr void + operator()(I8& e, const I32& c, const I8& d) const + { + // Scale AxB result with alpha + const F32 c_scale = ck::type_convert(c) * alpha; + + // Scale D with beta + const F32 d_scale = ck::type_convert(d) * beta; + + // Perform addition operation + F32 temp = c_scale + d_scale; + + // Perform RELU operation + temp = temp > 0 ? temp : 0; + + // Perform rounding operation + temp = temp > 127 ? 127 : temp; + + // Return to E + e = ck::type_convert(temp); + } + + F32 alpha; + F32 beta; +}; +``` + +The original input tensors need to be padded to meet GPU tile-based parallelism. + +```c++ +static constexpr auto GemmDefault = ck::tensor_operation::device::GemmSpecialization::MNKPadding; +``` + +The template parameters of the target fundamental instance are initialized with the above parameters and includes default tunable parameters. For specific tuning methods, see [Tunable parameters](#tunable-parameters). + +```c++ +using DeviceOpInstance = ck::tensor_operation::device::DeviceBatchedGemmMultiD_Xdl< + // Tensor layout + ALayout, BLayout, DsLayout, ELayout, + // Tensor data type + ADataType, BDataType, AccDataType, CShuffleDataType, DsDataType, EDataType, + // Tensor operation + AElementOp, BElementOp, CDEElementOp, + // Padding strategy + GemmDefault, + // Tunable parameters + tunable parameters>; +``` + +Return the address of the first element of tensors: + +```c++ + auto A_ref = A.data_ptr(); + auto B_ref = B.data_ptr(); + auto D0_ref = D.data_ptr(); + auto E_ref = E.data_ptr(); +``` + +The fundamental instance is then initialized and run with actual arguments: + +```c++ + auto device_op = DeviceOpInstance{}; + auto invoker = device_op.MakeInvoker(); + auto argument = device_op.MakeArgument( + A_ref, B_ref, {D0_ref}, E_ref, + M, N, K, + batch_count, + stride_A, stride_B, {stride_D0}, stride_E, + batch_stride_A, batch_stride_B, {batch_stride_D0}, batch_stride_E, + AElementOp{}, BElementOp{}, CDEElementOp{alpha, beta}); + +invoker.Run(argument, StreamConfig{nullptr, 0}); +``` + +The output of the fundamental instance is a calculated batched matrix E (batch, M, N). Before the return, it needs to be converted to a 2-D matrix if a normal GEMM result is required. + +```c++ +// Convert (1, M, N) to (M, N) +return E.squeeze(0); +``` + +### Binding to Python + +Since these functions are written in C++ and `torch::Tensor`, you can use `pybind11` to bind the functions and import them as Python modules. For the example, the necessary binding code for exposing the functions in the table spans but a few lines. + +```c++ +#include + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m){ + m.def("linear_ab_i8_de_f32", &linear_ab_i8_de_f32); + m.def("linear_relu_abde_i8", &linear_relu_abde_i8); + m.def("linear_abde_i8", &linear_abde_i8); + m.def("bmm_abe_i8", &bmm_abe_i8); + m.def("bmm_ab_i8_e_f32", &bmm_ab_i8_e_f32); +} +``` + +Build the C++ extension by writing a `setup.py` script that uses `setuptools` to compile the C++ code. A reference implementation of the `setup.py` script is as follows. + +```python +import os +from setuptools import setup, find_packages +from torch.utils import cpp_extension +from torch.utils.cpp_extension import BuildExtension + +os.environ["CC"] = "hipcc" +os.environ["CXX"] = "hipcc" + +sources = [ + 'torch_int/kernels/linear.cpp', + 'torch_int/kernels/bmm.cpp', + 'torch_int/kernels/pybind.cpp', +] + +include_dirs = ['torch_int/kernels/include'] +extra_link_args = ['libutility.a'] +extra_compile_args = ['-O3','-DNDEBUG', '-std=c++17', '--offload-arch=gfx942', '-DCK_ENABLE_INT8', '-D__HIP_PLATFORM_AMD__=1'] + +setup( + name='torch_int', + ext_modules=[ + cpp_extension.CUDAExtension( + name='torch_int.rocm', + sources=sources, + include_dirs=include_dirs, + extra_link_args=extra_link_args, + extra_compile_args=extra_compile_args + ), + ], + cmdclass={ + 'build_ext': BuildExtension.with_options(use_ninja=False) + }, + packages=find_packages( + exclude=['notebook', 'scripts', 'tests']), +) +``` + +Run `python setup.py install` to build and install the extension. It should look something like Figure 6: + + +```{figure} ../../data/how-to/fine-tuning-llms/ck-compilation.jpg +Compilation and installation of the INT8 kernels. +``` + +### INT8 model inference and performance + +The implementation architecture of running SmoothQuant models on MI300X GPUs is illustrated in Figure 7, where (a) shows the decoder layer composition components of the target model, (b) shows the major implementation class for the decoder layer components, and \(c\) denotes the underlying GPU kernels implemented by CK instance. + + +```{figure} ../../data/how-to/fine-tuning-llms/ck-inference_flow.jpg +The implementation architecture of running SmoothQuant models on AMD MI300X accelerators. +``` + +For the target [SQ quantized model](https://huggingface.co/mit-han-lab/opt-13b-smoothquant), each decoder layer contains three major components: attention calculation, layer normalization, and linear transformation in fully connected layers. The corresponding implementation classes for these components are: + +- `Int8OPTAttention` +- `W8A8B8O8LinearReLU` +- `W8A8BF32OF32Linear` + + These classes' underlying implementation logits will harness the functions in previous table. Note that for the example, the `LayerNormQ` module is implemented by the torch native module. + +Testing environment: +The hardware platform used for testing equips with 256 AMD EPYC 9534 64-Core Processor, 8 AMD Instinct MI300X accelerators and 1.5T memory. The testing was done in a publicly available Docker image from Docker Hub: +[`rocm/pytorch:rocm6.1_ubuntu22.04_py3.10_pytorch_2.1.2`](https://hub.docker.com/layers/rocm/pytorch/rocm6.1_ubuntu22.04_py3.10_pytorch_2.1.2/images/sha256-f6ea7cee8aae299c7f6368187df7beed29928850c3929c81e6f24b34271d652b) + +The tested models are OPT-1.3B, 2.7B, 6.7B and 13B FP16 models and the corresponding SmoothQuant INT8 OPT models were obtained from Hugging Face. + +Note that since the default values were used for the tunable parameters of the fundamental instance, the performance of the INT8 kernel is suboptimal. + +Figure 8 shows the performance comparisons between the original FP16 and the SmoothQuant-quantized INT8 models on a single MI300X accelerator. The GPU memory footprints of SmoothQuant-quantized models are significantly reduced. It also indicates the per-sample inference latency is significantly reduced for all SmoothQuant-quantized OPT models (illustrated in (b)). Notably, the performance of the CK instance-based INT8 kernel steadily improves with an increase in model size. + + +```{figure} ../../data/how-to/fine-tuning-llms/ck-comparisons.jpg +Performance comparisons between the original FP16 and the SmoothQuant-quantized INT8 models on a single MI300X accelerator. +``` + +For accuracy comparisons between the original FP16 and INT8 models, the evaluation is done by using the first 1,000 samples from the LAMBADA dataset's validation set. We employ the same Last Token Prediction Accuracy method introduced in [SmoothQuant Real-INT8 Inference for PyTorch](https://github.com/mit-han-lab/smoothquant/blob/main/examples/smoothquant_opt_real_int8_demo.ipynb) as our evaluation metric. The comparison results are shown in Table 2. + +:::{table} The inference accuracy comparisons of SmoothQuant quantized models on Instinct MI300X. + +| Models | Hugging Face FP16 model accuracy | SmoothQuant quantized INT8 model accuracy | +|:-----------------|----------------------------------------|---------------------------------------------| +| opt-1.3B | 0.72 | 0.70 | +| opt-2.7B | 0.76 | 0.75 | +| opt-6.7B | 0.80 | 0.79 | +| opt-13B | 0.79 | 0.77 | +::: + +## Conclusion + +CK provides a rich set of template parameters for generating flexible accelerated computing kernels for difference application scenarios. + +CK supports multiple instruction sets of AMD Instinct GPUs, operator fusion and different data precisions. Its composability helps users quickly construct operator performance verification. + +With CK, you can build more effective AI applications with higher flexibility and better performance on different AMD accelerator platforms. diff --git a/docs/how-to/fine-tuning-llms/overview.rst b/docs/how-to/fine-tuning-llms/overview.rst new file mode 100644 index 0000000000..90330cdbd2 --- /dev/null +++ b/docs/how-to/fine-tuning-llms/overview.rst @@ -0,0 +1,104 @@ +.. meta:: + :description: How to fine-tune LLMs with ROCm + :keywords: ROCm, LLM, fine-tuning, usage, tutorial, optimzation, LoRA, walkthrough + +*************************************** +Conceptual overview of fine-tuning LLMs +*************************************** + +Large language models (LLMs) are trained on massive amounts of text data to generate coherent and fluent text. The +underlying *transformer* architecture is the fundamental building block of all LLMs. Transformers serve as the +enable LLMs to understand and generate text by capturing contextual relationships and long-range dependencies. To better +understand the philosophy of the transformer architecture, review the foundational +`Attention is all you need `_ paper. + +By further training pre-trained LLMs, the fine-tuned model can gain knowledge related to specific fields or tasks, +thereby significantly improving its performance in that field or task. The core idea of fine-tuning is to use the +parameters of the pre-trained model as the starting point for new tasks and shape it through a small amount of +specific domain or task data, expanding the original model's capability to new tasks or datasets. + +Fine-tuning can effectively improve the performance of existing pre-trained models in specific application scenarios. +Continuous training and adjustment of the parameters of the base model in the target domain or task can better capture +the semantic characteristics and patterns in specific scenarios, thereby significantly improving the key indicators of +the model in that domain or task. For example, by fine-tuning the Llama 2 model, its performance in certain applications +can be improve over the base model. + +.. _fine-tuning-llms-concept-challenge: + +The challenge of fine-tuning models +=================================== + +However, the computational cost of fine-tuning is still high, especially for complex models and large datasets, which +poses distinct challenges related to substantial computational and memory requirements. This might be a barrier for +accelerators or GPUs with low computing power or limited device memory resources. + +For example, suppose we have a language model with 7 billion (7B) parameters, represented by a weight matrix :math:`W`. +During backpropagation, the model needs to learn a :math:`ΔW` matrix, which updates the original weights to minimize the +value of the loss function. + +The weight update is as follows: :math:`W_{updated} = W + ΔW`. + +If the weight matrix :math:`W` contains 7B parameters, then the weight update matrix :math:`ΔW` should also +contain 7B parameters. Therefore, the :math:`ΔW` calculation is computationally and memory intensive. + +.. figure:: ../../data/how-to/fine-tuning-llms/weight-update.png + :alt: Weight update diagram + + (a) Weight update in regular fine-tuning. (b) Weight update in LoRA where the product of matrix A (:math:`M\times K`) + and matrix B (:math:`K\times N`) is :math:`ΔW(M\times N)`; dimension K is a hyperparameter. By representing + :math:`ΔW` as the product of two smaller matrices (A and B) with a lower rank K, the number of trainable parameters + is significantly reduced. + +.. _fine-tuning-llms-concept-optimizations: + +Optimizations for model fine-tuning +=================================== + +Low-Rank Adaptation (LoRA) is a technique allowing fast and cost-effective fine-tuning of state-of-the-art LLMs that can +overcome this issue of high memory consumption. + +LoRA accelerates the adjustment process and reduces related memory costs. To be precise, LoRA decomposes the portion of +weight changes :math:`ΔW` into high-precision low-rank representations, which do not require the calculations of all +:math:`ΔW`. It learns the decomposition representation of :math:`ΔW` during training, as shown in +:ref:`the weight update diagram `. This is how LoRA saves on +computing resources. + +LoRA is integrated into the `Hugging Face Parameter-Efficient Fine-Tuning (PEFT) +`_ library, as well as other computation and memory efficiency optimization +variants for model fine-tuning such as `AdaLoRA `_. This +library efficiently adapts large pre-trained models to various downstream applications without fine-tuning all model +parameters. PEFT methods only fine-tune a few model parameters, significantly decreasing computational and storage +costs while yielding performance comparable to a fully fine-tuned model. PEFT is integrated with the `Hugging Face +Transformers `_ library, providing a faster and easier way to load, +train, and use large models for inference. + +To simplify running a fine-tuning implementation, the `Transformer Reinforcement Learning (TRL) +`_ library provides a set of tools to train transformer language models with +reinforcement learning, from the Supervised Fine-Tuning step (SFT), Reward Modeling step (RM), to the Proximal Policy +Optimization (PPO) step. The ``SFTTrainer`` API in TRL encapsulates these PEFT optimizations so you can easily import +their custom training configuration and run the training process. + +.. _fine-tuning-llms-walkthrough-desc: + +Walkthrough +=========== + +To demonstrate the benefits of LoRA and the ideal compute compatibility of using PEFT and TRL libraries on AMD +ROCm-compatible accelerators and GPUs, let's step through a comprehensive implementation of the fine-tuning process +using the Llama 2 7B model with LoRA tailored specifically for question-and-answer tasks on AMD MI300X accelerators. + +Before starting, review and understand the key components of this walkthrough: + +- `Llama 2 `_: a family of large language models developed and publicly released by + Meta. Its variants range in scale from 7 billion to 70 billion parameters. + +- Fine-tuning: a critical process that refines LLMs for specialized tasks and optimizes performance. + +- LoRA: a memory-efficient implementation of LLM fine-tuning that significantly reduces the number of trainable + parameters. + +- `SFTTrainer `_: an optimized + trainer with a simple interface to easily fine-tune pre-trained models with PEFT adapters, for example, LoRA, for + memory efficiency purposes on a custom dataset. + +Continue the walkthrough in :doc:`Fine-tuning and inference `. diff --git a/docs/how-to/fine-tuning-llms/profiling-and-debugging.rst b/docs/how-to/fine-tuning-llms/profiling-and-debugging.rst new file mode 100644 index 0000000000..4371fca4ae --- /dev/null +++ b/docs/how-to/fine-tuning-llms/profiling-and-debugging.rst @@ -0,0 +1,217 @@ +.. meta:: + :description: How to fine-tune LLMs with ROCm + :keywords: ROCm, LLM, fine-tuning, usage, tutorial, profiling, debugging, performance, Triton + +*********************** +Profiling and debugging +*********************** + +This section discusses profiling and debugging tools and some of their common usage patterns with ROCm applications. + +PyTorch Profiler +================ + +`PyTorch Profiler `_ can be invoked inside Python scripts, letting you +collect CPU and GPU performance metrics while the script is running. See the `PyTorch Profiler tutorial +`_ for more information. + +You can then visualize and view these metrics using an open-source profile visualization tool like +`Perfetto UI `_. + +#. Use the following snippet to invoke PyTorch Profiler in your code. + + .. code-block:: python + + import torch + import torchvision.models as models + from torch.profiler import profile, record_function, ProfilerActivity + model = models.resnet18().cuda() + inputs = torch.randn(2000, 3, 224, 224).cuda() + + with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof: + with record_function("model_inference"): + model(inputs) + prof.export_chrome_trace("resnet18_profile.json") + +#. Profile results in ``resnet18_profile.json`` can be viewed by the Perfetto visualization tool. Go to + ``__ and import the file. In your Perfetto visualization, you'll see that the upper section + shows transactions denoting the CPU activities that launch GPU kernels while the lower section shows the actual GPU + activities where it processes the ``resnet18`` inferences layer by layer. + + .. figure:: ../../data/how-to/fine-tuning-llms/perfetto-trace.svg + + Perfetto trace visualization example. + +ROCm profiling tools +==================== + +Heterogenous systems, where programs run on both CPUs and GPUs, introduce additional complexities. Understanding the +critical path and kernel execution is all the more important; so, performance tuning is a necessary component in the +benchmarking process. + +With AMD's profiling tools, developers are able to gain important insight into how efficiently their application is +using hardware resources and effectively diagnose potential bottlenecks contributing to poor performance. Developers +working with AMD Instinct accelerators have multiple tools depending on their specific profiling needs; these are: + +* :ref:`ROCProfiler ` +* :ref:`Omniperf ` +* :ref:`Omnitrace ` + +.. _fine-tuning-llms-profiling-rocprof: + +ROCProfiler +----------- +:doc:`ROCProfiler ` is primarily a low-level API for accessing and extracting GPU hardware performance +metrics, commonly called *performance counters*. These counters quantify the performance of the underlying architecture +showcasing which pieces of the computational pipeline and memory hierarchy are being utilized. + +Your ROCm installation contains a script or executable command called ``rocprof`` which provides the ability to list all +available hardware counters for your specific accelerator or GPU, and run applications while collecting counters during +their execution. + +This ``rocprof`` utility also depends on the :doc:`ROCTracer and ROC-TX libraries `, giving it the +ability to collect timeline traces of the accelerator software stack as well as user-annotated code regions. + +.. note:: + + ``rocprof`` is a CLI-only utility so input and output takes the format of ``.txt`` and CSV files. These + formats provide a raw view of the data and puts the onus on the user to parse and analyze. Therefore, ``rocprof`` + gives the user full access and control of raw performance profiling data, but requires extra effort to analyze the + collected data. + +.. _fine-tuning-llms-profiling-omniperf: + +Omniperf +-------- +`Omniperf `_ is a system performance profiler for high-performance computing (HPC) and +machine learning (ML) workloads using Instinct accelerators. Under the hood, Omniperf uses +:ref:`ROCProfiler ` to collect hardware performance counters. The Omniperf tool performs +system profiling based on all approved hardware counters for Instinct +accelerator architectures. It provides high level performance analysis features including System Speed-of-Light, IP +block Speed-of-Light, Memory Chart Analysis, Roofline Analysis, Baseline Comparisons, and more. + +Omniperf takes the guesswork out of profiling by removing the need to provide text input files with lists of counters +to collect and analyze raw CSV output files as is the case with ROC-profiler. Instead, Omniperf automates the collection +of all available hardware counters in one command and provides a graphical interface to help users understand and +analyze bottlenecks and stressors for their computational workloads on AMD Instinct accelerators. + +.. note:: + + Omniperf collects hardware counters in multiple passes, and will therefore re-run the application during each pass + to collect different sets of metrics. + +.. figure:: ../../data/how-to/fine-tuning-llms/omniperf-analysis.png + + Omniperf memory chat analysis panel. + +In brief, Omniperf provides details about hardware activity for a particular GPU kernel. It also supports both +a web-based GUI or command-line analyzer, depending on your preference. + +.. _fine-tuning-llms-profiling-omnitrace: + +Omnitrace +--------- + +`Omnitrace `_ is a comprehensive profiling and tracing tool for parallel applications, +including HPC and ML packages, written in C, C++, Fortran, HIP, OpenCL, and Python which execute on the CPU or CPU and +GPU. It is capable of gathering the performance information of functions through any combination of binary +instrumentation, call-stack sampling, user-defined regions, and Python interpreter hooks. + +Omnitrace supports interactive visualization of comprehensive traces in the web browser in addition to high-level +summary profiles with ``mean/min/max/stddev`` statistics. Beyond runtime +information, Omnitrace supports the collection of system-level metrics such as CPU frequency, GPU temperature, and GPU +utilization. Process and thread level metrics such as memory usage, page faults, context switches, and numerous other +hardware counters are also included. + +.. tip:: + + When analyzing the performance of an application, it is best not to assume you know where the performance + bottlenecks are and why they are happening. Omnitrace is the ideal tool for characterizing where optimization would + have the greatest impact on the end-to-end execution of the application and to discover what else is happening on the + system during a performance bottleneck. + +.. figure:: ../../data/how-to/fine-tuning-llms/omnitrace-timeline.png + + Omnitrace timeline trace example. + +For details usage and examples of using these tools, refer to the +`Introduction to profiling tools for AMD hardware `_ +developer blog. + +Debugging with ROCm Debug Agent +=============================== + +ROCm Debug Agent (:doc:`ROCdebug-agent `) is a library that can be loaded by the ROCm platform +runtime (:doc:`ROCr `) to provide the following functionalities for all AMD accelerators and GPUs +supported by the ROCm Debugger API (:doc:`ROCdbgapi `). + +* Print the state of all AMD accelerator or GPU wavefronts that caused a queue error; for example, causing a memory + violation, executing an ``s_trap2``, or executing an illegal instruction. + +* Print the state of all AMD accelerator or GPU wavefronts by sending a ``SIGQUIT`` signal to the process in question; + for example, by pressing ``Ctrl + \`` while the process is executing. + +Debugging memory access faults +------------------------------ + +Identifying a faulting kernel is often enough to triage a memory access fault. To that end, the +`ROCm Debug Agent `_ can trap a memory access fault and provide a dump of all +active wavefronts that caused the error as well as the name of the kernel. The +`AMD ROCm Debug Agent Library README `_ provides full +instructions, but in brief: + +* Compiling with ``-ggdb -O0`` is recommended but not required. + +* ``HSA_TOOLS_LIB=/opt/rocm/lib/librocm-debug-agent.so.2 HSA_ENABLE_DEBUG=1 ./my_program`` + +When the debug agent traps the fault, it will produce an extremely +verbose output of all wavefront registers and memory content. +Importantly, it also prints something like: + +.. code-block:: shell + + Disassembly for function vector_add_assert_trap(int*, int*, int*): + + code object: + file:////rocm-debug-agent/build/test/rocm-debug-agent-test#offset=14309&size=31336 + + loaded at: [0x7fd4f100c000-0x7fd4f100e070] + +The kernel name and the code object file should be listed. In the +example above, the kernel name is ``vector_add_assert_trap``, but this might +also look like: + +.. code-block:: shell + + Disassembly for function memory:///path/to/codeobject#offset=1234&size=567: + +In this case, it is an in-memory kernel that was generated at runtime. + +Using the following environment variable, the debug agent will save all code objects to the current directory (use +``--save-code-objects=[DIR]`` to place them in another location). The code objects will be renamed from the URI format +with special characters replaced by ``_``. + +.. code-block:: shell + + ROCM_DEBUG_AGENT_OPTIONS="--all --save-code-objects" + +Use the ``llvm-objdump`` command to disassemble the indicated in-memory +code object that has now been saved to disk. The name of the kernel is +often found inside the disassembled code object. + +.. code-block:: shell + + llvm-objdump --disassemble-all path/to/code-object.co + +Consider turning off memory caching strategies both within the ROCm +stack and PyTorch where possible. This will give the debug agent the +best chance at finding the memory fault where it originates. Otherwise, +it could be masked by writing past the end of a cached block within a +larger allocation. + +.. code-block:: shell + + PYTORCH_NO_HIP_MEMORY_CACHING=1 + + HSA_DISABLE_FRAGMENT_ALLOCATOR=1 + diff --git a/docs/how-to/fine-tuning-llms/single-gpu-fine-tuning-and-inference.rst b/docs/how-to/fine-tuning-llms/single-gpu-fine-tuning-and-inference.rst new file mode 100644 index 0000000000..48da84446f --- /dev/null +++ b/docs/how-to/fine-tuning-llms/single-gpu-fine-tuning-and-inference.rst @@ -0,0 +1,509 @@ +.. meta:: + :description: Model fine-tuning and inference on a single-GPU system + :keywords: ROCm, LLM, fine-tuning, usage, tutorial, single-GPU, LoRA, PEFT, inference + +**************************************************** +Fine-tuning and inference using a single accelerator +**************************************************** + +This section explains model fine-tuning and inference techniques on a single-accelerator system. See +:doc:`Multi-accelerator fine-tuning ` for a setup with multiple accelerators or +GPUs. + +.. _fine-tuning-llms-single-gpu-env: + +Environment setup +================= + +This section was tested using the following hardware and software environment. + +.. list-table:: + :stub-columns: 1 + + * - Hardware + - AMD Instinct MI300X accelerator + + * - Software + - ROCm 6.1, Ubuntu 22.04, PyTorch 2.1.2, Python 3.10 + + * - Libraries + - ``transformers`` ``datasets`` ``huggingface-hub`` ``peft`` ``trl`` ``scipy`` + + * - Base model + - ``meta-llama/Llama-2-7b-chat-hf`` + +.. _fine-tuning-llms-single-gpu-env-setup: + +Setting up the base implementation environment +---------------------------------------------- + +#. Install PyTorch for ROCm. Refer to the + :doc:`PyTorch installation guide `. For a consistent + installation, it’s recommended to use official ROCm prebuilt Docker images with the framework pre-installed. + +#. In the Docker container, check the availability of ROCm-capable accelerators using the following command. + + .. code-block:: shell + + rocm-smi -showproductname + + Your output should look like this: + + .. code-block:: shell + + ============================ ROCm System Management Interface ============================ + ====================================== Product Info ====================================== + GPU[0] : Card series: AMD Instinct MI300X OAM + GPU[0] : Card model: 0x74a1 + GPU[0] : Card vendor: Advanced Micro Devices, Inc. [AMD/ATI] + GPU[0] : Card SKU: MI3SRIOV + ========================================================================================== + ================================== End of ROCm SMI Log =================================== + +#. Check that your accelerators are available to PyTorch. + + .. code-block:: python + + import torch + print("Is a ROCm-GPU detected? ", torch.cuda.is_available()) + print("How many ROCm-GPUs are detected? ", torch.cuda.device_count()) + + If successful, your output should look like this: + + .. code-block:: shell + + >>> print("Is a ROCm-GPU detected? ", torch.cuda.is_available()) + Is a ROCm-GPU detected? True + >>> print("How many ROCm-GPUs are detected? ", torch.cuda.device_count()) + How many ROCm-GPUs are detected? 4 + +#. Install the required dependencies. + + bitsandbytes is a library that facilitates quantization to improve the efficiency of deep learning models. Learn more + about its use in :doc:`model-quantization`. + + See the :ref:`Optimizations for model fine-tuning ` for a brief discussion on + PEFT and TRL. + + .. code-block:: shell + + # Install `bitsandbytes` for ROCm 6.0+, use -DBNB_ROCM_ARCH to target specific GPU arch + git clone --recurse https://github.com/ROCm/bitsandbytes.git + cd bitsandbytes + git checkout rocm_enabled + pip install -r requirements-dev.txt + cmake -DBNB_ROCM_ARCH="gfx942" -DCOMPUTE_BACKEND=hip -S . + python setup.py install + + # To leverage the SFTTrainer in TRL for model fine-tuning + pip install trl + + # To leverage PEFT for efficiently adapting pre-trained language models + pip install peft + + # Install the other dependencies: + pip install transformers, datasets, huggingface-hub, scipy + +#. Check that the required packages can be imported. + + .. code-block:: python + + import torch + from datasets import load_dataset + from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + TrainingArguments + ) + from peft import LoraConfig + from trl import SFTTrainer + +.. _fine-tuning-llms-single-gpu-download-model-dataset: + +Download the base model and fine-tuning dataset +----------------------------------------------- + +#. Request to access to download the `Meta's official Llama model `_ from Hugging + Face. After permission is granted, log in with the following command using your personal access tokens: + + .. code-block:: shell + + huggingface-cli login + + .. note:: + + You can also use the `NousResearch Llama-2-7b-chat-hf `_ + as a substitute. It has the same model weights as the original. + +#. Run the following code to load the base model and tokenizer. + + .. code-block:: python + + # Base model and tokenizer names + base_model_name = "meta-llama/Llama-2-7b-chat-hf" + + # Load base model to GPU memory + device = "cuda:0" + base_model = AutoModelForCausalLM.from_pretrained(base_model_name, trust_remote_code = True).to(device) + + # Load tokenizer + tokenizer = AutoTokenizer.from_pretrained( + base_model_name, + trust_remote_code = True) + tokenizer.pad_token = tokenizer.eos_token + tokenizer.padding_side = "right" + +#. Now, let's fine-tune the base model for a question-and-answer task using a small dataset called + `mlabonne/guanaco-llama2-1k `_, which is a 1000 sample + subset of the `timdettmers/openassistant-guanaco `_ dataset. + + .. code-block:: + + # Dataset for fine-tuning + training_dataset_name = "mlabonne/guanaco-llama2-1k" + training_dataset = load_dataset(training_dataset_name, split = "train") + + # Check the data + print(training_dataset) + + # #11 is a QA sample in English + print(training_dataset[11]) + +#. With the base model and the dataset, let's start fine-tuning! + +.. _fine-tuning-llms-single-gpu-configure-params: + +Configure fine-tuning parameters +-------------------------------- + +To set up ``SFTTrainer`` parameters, you can use the following code as reference. + +.. code-block:: python + + # Training Params for SFTTrainer + training_arguments = TrainingArguments( + output_dir = "./results", + num_train_epochs = 1, + per_device_train_batch_size = 4, + gradient_accumulation_steps = 1, + optim = "paged_adamw_32bit", + save_steps = 50, + logging_steps = 50, + learning_rate = 4e-5, + weight_decay = 0.001, + fp16=False, + bf16=False, + max_grad_norm = 0.3, + max_steps = -1, + warmup_ratio = 0.03, + group_by_length = True, + lr_scheduler_type = "constant", + report_to = "tensorboard" + ) + +.. _fine-tuning-llms-single-gpu-start: + +Fine-tuning +=========== + +In this section, you'll see two ways of training: with the LoRA technique and without. See :ref:`Optimizations for model +fine-tuning ` for an introduction to LoRA. Training with LoRA uses the +``SFTTrainer`` API with its PEFT integration. Training without LoRA forgoes these benefits. + +Compare the number of trainable parameters and training time under the two different methodologies. + +.. tab-set:: + + .. tab-item:: Fine-tuning with LoRA and PEFT + :sync: with + + 1. Configure LoRA using the following code snippet. + + .. code-block:: python + + peft_config = LoraConfig( + lora_alpha = 16, + lora_dropout = 0.1, + r = 64, + bias = "none", + task_type = "CAUSAL_LM" + ) + # View the number of Trainable Params + from peft import get_peft_model + peft_model = get_peft_model(base_model, peft_config) + peft_model.print_trainable_parameters() + + The output should look like this. Compare the number of trainable parameters to that when fine-tuning without + LoRA and PEFT. + + .. code-block:: shell + + trainable params: 33,554,432 || all params: 6,771,970,048 || trainable%: 0.49548996469513035 + + 2. Initialize ``SFTTrainer`` with a PEFT LoRA configuration and run the trainer. + + .. code-block:: python + + # Initialize a sft trainer + sft_trainer = SFTTrainer( + model = base_model, + train_dataset = training_dataset, + peft_config = peft_config, + dataset_text_field = "text", + tokenizer = tokenizer, + args = training_arguments + ) + + # Run the trainer + sft_trainer.train() + + The output should look like this: + + .. code-block:: shell + + {'loss': 1.5973, 'grad_norm': 0.25271978974342346, 'learning_rate': 4e-05, 'epoch': 0.16} + {'loss': 2.0519, 'grad_norm': 0.21817368268966675, 'learning_rate': 4e-05, 'epoch': 0.32} + {'loss': 1.6147, 'grad_norm': 0.3046981394290924, 'learning_rate': 4e-05, 'epoch': 0.48} + {'loss': 1.4124, 'grad_norm': 0.11534837633371353, 'learning_rate': 4e-05, 'epoch': 0.64} + {'loss': 1.5627, 'grad_norm': 0.09108350425958633, 'learning_rate': 4e-05, 'epoch': 0.8} + {'loss': 1.417, 'grad_norm': 0.2536439299583435, 'learning_rate': 4e-05, 'epoch': 0.96} + {'train_runtime': 197.4947, 'train_samples_per_second': 5.063, 'train_steps_per_second': 0.633, 'train_loss': 1.6194254455566406, 'epoch': 1.0} + 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████| 125/125 [03:17<00:00, 1.58s/it] + + .. tab-item:: Fine-tuning without LoRA and PEFT + :sync: without + + 1. Use the following code to get started. + + .. code-block:: python + + def print_trainable_parameters(model): + # Prints the number of trainable parameters in the model. + trainable_params = 0 + all_param = 0 + for _, param in model.named_parameters(): + all_param += param.numel() + if param.requires_grad: + trainable_params += param.numel() + print(f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param:.2f}") + + sft_trainer.peft_config = None + print_trainable_parameters(sft_trainer.model) + + The output should look like this. Compare the number of trainable parameters to that when fine-tuning with LoRA + and PEFT. + + .. code-block:: shell + + trainable params: 6,738,415,616 || all params: 6,738,415,616 || trainable%: 100.00 + + + 2. Run the trainer. + + .. code-block:: python + + # Trainer without LoRA config + trainer_full = SFTTrainer( + model = base_model, + train_dataset = training_dataset, + dataset_text_field = "text", + tokenizer = tokenizer, + args = training_arguments + ) + + # Training + trainer_full.train() + + The output should look like this: + + .. code-block:: shell + + {'loss': 1.5975, 'grad_norm': 0.25113457441329956, 'learning_rate': 4e-05, 'epoch': 0.16} + {'loss': 2.0524, 'grad_norm': 0.2180655151605606, 'learning_rate': 4e-05, 'epoch': 0.32} + {'loss': 1.6145, 'grad_norm': 0.2949850261211395, 'learning_rate': 4e-05, 'epoch': 0.48} + {'loss': 1.4118, 'grad_norm': 0.11036080121994019, 'learning_rate': 4e-05, 'epoch': 0.64} + {'loss': 1.5595, 'grad_norm': 0.08962831646203995, 'learning_rate': 4e-05, 'epoch': 0.8} + {'loss': 1.4119, 'grad_norm': 0.25422757863998413, 'learning_rate': 4e-05, 'epoch': 0.96} + {'train_runtime': 419.5154, 'train_samples_per_second': 2.384, 'train_steps_per_second': 0.298, 'train_loss': 1.6171623611450194, 'epoch': 1.0} + 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████| 125/125 [06:59<00:00, 3.36s/it] + +.. _fine-tuning-llms-single-gpu-saving: + +Saving adapters or fully fine-tuned models +------------------------------------------ + +PEFT methods freeze the pre-trained model parameters during fine-tuning and add a smaller number of trainable +parameters, namely the adapters, on top of it. The adapters are trained to learn specific task information. The adapters +trained with PEFT are usually an order of magnitude smaller than the full base model, making them convenient to share, +store, and load. + +.. tab-set:: + + .. tab-item:: Saving a PEFT adapter + :sync: with + + If you're using LoRA and PEFT, use the following code to save a PEFT adapter to your system once the fine-tuning + is completed. + + .. code-block:: python + + # PEFT adapter name + adapter_name = "llama-2-7b-enhanced-adapter" + + # Save PEFT adapter + sft_trainer.model.save_pretrained(adapter_name) + + The saved PEFT adapter should look like this on your system: + + .. code-block:: shell + + # Access adapter directory + cd llama-2-7b-enhanced-adapter + + # List all adapter files + README.md adapter_config.json adapter_model.safetensors + + .. tab-item:: Saving a fully fine-tuned model + :sync: without + + If you're not using LoRA and PEFT so there is no PEFT LoRA configuration used for training, use the following code + to save your fine-tuned model to your system. + + .. code-block:: python + + # fully fine-tuned model name + new_model_name = "llama-2-7b-enhanced" + + # Save the fully fine-tuned model + full_trainer.model.save_pretrained(new_model_name) + + The saved new full model should look like this on your system: + + .. code-block:: shell + + # Access new model directory + cd llama-2-7b-enhanced + + # List all model files + config.json model-00002-of-00006.safetensors model-00005-of-00006.safetensors + generation_config.json model-00003-of-00006.safetensors model-00006-of-00006.safetensors + model-00001-of-00006.safetensors model-00004-of-00006.safetensors model.safetensors.index.json + +.. note:: + + PEFT adapters can’t be loaded by ``AutoModelForCausalLM`` from the Transformers library as they do not contain + full model parameters and model configurations, for example, ``config.json``. To use it as a normal transformer + model, you need to merge them into the base model. + +Basic model inference +===================== + +A trained model can be classified into one of three types: + +* A PEFT adapter + +* A pre-trained language model in Hugging Face + +* A fully fine-tuned model not using PEFT + +Let's look at achieving model inference using these types of models. + +.. tab-set:: + + .. tab-item:: Inference using PEFT adapters + + To use PEFT adapters like a normal transformer model, you can run the generation by loading a base model along with PEFT + adapters as follows. + + .. code-block:: python + + from peft import PeftModel + from transformers import AutoModelForCausalLM + + # Set the path of the model or the name on Hugging face hub + base_model_name = "meta-llama/Llama-2-7b-chat-hf" + + # Set the path of the adapter + adapter_name = "Llama-2-7b-enhanced-adpater" + + # Load base model + base_model = AutoModelForCausalLM.from_pretrained(base_model_name) + + # Adapt the base model with the adapter + new_model = PeftModel.from_pretrained(base_model, adapter_name) + + # Then, run generation as the same with a normal model outlined in 2.1 + + The PEFT library provides a ``merge_and_unload`` method, which merges the adapter layers into the base model. This is + needed if someone wants to save the adapted model into local storage and use it as a normal standalone model. + + .. code-block:: python + + # Load base model + base_model = AutoModelForCausalLM.from_pretrained(base_model_name) + + # Adapt the base model with the adapter + new_model = PeftModel.from_pretrained(base_model, adapter_name) + + # Merge adapter + model = model.merge_and_unload() + + # Save the merged model into local + model.save_pretrained("merged_adpaters") + + .. tab-item:: Inference using pre-trained or fully fine-tuned models + + If you have a fully fine-tuned model not using PEFT, you can load it like any other pre-trained language model in + `Hugging Face Hub `_ using the `Transformers + `_ library. + + .. code-block:: python + + # Import relevant class for loading model and tokenizer + from transformers import AutoTokenizer, AutoModelForCausalLM + + # Set the pre-trained model name on Hugging face hub + model_name = "meta-llama/Llama-2-7b-chat-hf" + + # Set device type + device = "cuda:0" + + # Load model and tokenizer + model = AutoModelForCausalLM.from_pretrained(model_name).to(device) + tokenizer = AutoTokenizer.from_pretrained(model_name) + + # Input prompt encoding + query = "What is a large language model?" + inputs = tokenizer.encode(query, return_tensors="pt").to(device) + + # Token generation + outputs = model.generate(inputs) + + # Outputs decoding + print(tokenizer.decode(outputs[0])) + + In addition, pipelines from Transformers offer simple APIs to use pre-trained models for different tasks, including + sentiment analysis, feature extraction, question answering and so on. You can use the pipeline abstraction to achieve + model inference easily. + + .. code-block:: python + + # Import relevant class for loading model and tokenizer + from transformers import pipeline + + # Set the path of your model or the name on Hugging face hub + model_name_or_path = "meta-llama/Llama-2-7b-chat-hf" + + # Set pipeline + # A positive device value will run the model on associated CUDA device id + pipe = pipeline("text-generation", model=model_name_or_path, device=0) + + # Token generation + print(pipe("What is a large language model?")[0]["generated_text"]) + +If using multiple accelerators, see +:ref:`Multi-accelerator fine-tuning and inference ` to explore +popular libraries that simplify fine-tuning and inference in a multi-accelerator system. + +Read more about inference frameworks like vLLM and Hugging Face TGI in +:doc:`LLM inference frameworks `. diff --git a/docs/how-to/rocm-for-ai/train-a-model.rst b/docs/how-to/rocm-for-ai/train-a-model.rst index f9c5854451..d7db257ca2 100644 --- a/docs/how-to/rocm-for-ai/train-a-model.rst +++ b/docs/how-to/rocm-for-ai/train-a-model.rst @@ -107,7 +107,10 @@ for more information about running AMP on an AMD accelerator. Fine-tuning your model ====================== -ROCm supports multiple fine-tuning techniques, for example, LoRA, QLoRA, PEFT, and FSDP. +ROCm supports multiple techniques for :ref:`optimizing fine-tuning `, for +example, LoRA, QLoRA, PEFT, and FSDP. + +Learn more about challenges and solutions for model fine-tuning in :doc:`../fine-tuning-llms/index`. The following developer blogs showcase examples of how to fine-tune a model on an AMD accelerator or GPU. diff --git a/docs/index.md b/docs/index.md index 0f37a3c6ae..57965eb4d5 100644 --- a/docs/index.md +++ b/docs/index.md @@ -92,6 +92,7 @@ Our documentation is organized into the following categories: :padding: 2 * [Using ROCm for AI](./how-to/rocm-for-ai/index.rst) +* [Fine-tuning LLMs with ROCm](./how-to/fine-tuning-llms/index.rst) * [System tuning for various architectures](./how-to/tuning-guides.md) * [MI100](./how-to/tuning-guides/mi100.md) * [MI200](./how-to/tuning-guides/mi200.md) diff --git a/docs/sphinx/_toc.yml.in b/docs/sphinx/_toc.yml.in index a76f9dd9e1..3e2a0ac05b 100644 --- a/docs/sphinx/_toc.yml.in +++ b/docs/sphinx/_toc.yml.in @@ -58,6 +58,27 @@ subtrees: - file: how-to/rocm-for-ai/train-a-model.rst - file: how-to/rocm-for-ai/hugging-face-models.rst - file: how-to/rocm-for-ai/deploy-your-model.rst + - file: how-to/fine-tuning-llms/index.rst + title: Fine-tuning LLMs with ROCm + subtrees: + - entries: + - file: how-to/fine-tuning-llms/overview.rst + title: Conceptual overview + - file: how-to/fine-tuning-llms/fine-tuning-and-inference.rst + subtrees: + - entries: + - file: how-to/fine-tuning-llms/single-gpu-fine-tuning-and-inference.rst + title: Using a single accelerator + - file: how-to/fine-tuning-llms/multi-gpu-fine-tuning-and-inference.rst + title: Using multiple accelerators + - file: how-to/fine-tuning-llms/model-quantization.rst + - file: how-to/fine-tuning-llms/model-acceleration-libraries.rst + - file: how-to/fine-tuning-llms/llm-inference-frameworks.rst + - file: how-to/fine-tuning-llms/optimizing-with-composable-kernel.md + title: Optimizing with Composable Kernel + - file: how-to/fine-tuning-llms/optimizing-triton-kernel.rst + title: Optimizing Triton kernels + - file: how-to/fine-tuning-llms/profiling-and-debugging.rst - file: how-to/tuning-guides.md title: System optimization subtrees: