Package: xfastertransformer
xFasterTransformerxFasterTransformer is an exceptionally optimized solution for large language models (LLM) on the X86 platform, which is similar to FasterTransformer on the GPU platform. xFasterTransformer is able to operate in distributed mode across multiple sockets and nodes to support inference on larger models. Additionally, it provides both C++ and Python APIs, spanning from high-level to low-level interfaces, making it easy to adopt and integrate.Table of ContentsxFasterTransformerTable of ContentsModels overviewModel support matrixDataType support listDocumentsInstallationFrom PyPIUsing DockerBuilt from sourcePrepare EnvironmentManuallyDockerHow to buildModels PreparationAPI usagePython API(PyTorch)C++ APIHow to runSingle rankMulti ranksCommand lineCodePythonC++Web DemoBenchmarkSupportQ&AModels overviewLarge Language Models (LLMs) develops very fast and are more widely used in many AI scenarios. xFasterTransformer is an optimized solution for LLM inference using the mainstream and popular LLM models on Xeon. xFasterTransformer fully leverages the hardware capabilities of Xeon platforms to achieve the high performance and high scalability of LLM inference both on single socket and multiple sockets/multiple nodes.xFasterTransformer provides a series of APIs, both of C++ and Python, for end users to integrate xFasterTransformer into their own solutions or services directly. Many kinds of example codes are also provided to demonstrate the usage. Benchmark codes and scripts are provided for users to show the performance. Web demos for popular LLM models are also provided.Model support matrixModelsFrameworkDistributionPyTorchC++ChatGLM✔✔✔ChatGLM2✔✔✔ChatGLM3✔✔✔Llama✔✔✔Llama2✔✔✔Baichuan✔✔✔QWen✔✔✔SecLLM(YaRN-Llama)✔✔✔Opt✔✔✔DataType support listFP16BF16INT8W8A8INT4NF4BF16_FP16BF16_INT8BF16_W8A8BF16_INT4BF16_NF4W8A8_INT8W8A8_int4W8A8_NF4DocumentsxFasterTransformer Documents andWikiprovides the following resources:An introduction to xFasterTransformer.Comprehensive API references for both high-level and low-level interfaces in C++ and PyTorch.Practical API usage examples for xFasterTransformer in both C++ and PyTorch.InstallationFrom PyPIpipinstallxfastertransformerUsing Dockerdockerpullintel/xfastertransformer:latestBuilt from sourcePrepare EnvironmentManuallyPyTorchv2.0 (When using the PyTorch API, it's required, but it's not needed when using the C++ API.)pipinstalltorch--index-urlhttps://download.pytorch.org/whl/cpuDockerBuild docker image from Dockerfiledockerbuild\-fdockerfiles/Dockerfile\--build-arg"HTTP_PROXY=${http_proxy}"\--build-arg"HTTPS_PROXY=${https_proxy}"\-tintel/xfastertransformer:dev-ubuntu22.04.Then run the docker with the command (Assume model files are in/data/directory):dockerrun-it\--namexfastertransformer-dev\--privileged\--shm-size=16g\-v"${PWD}":/root/xfastertransformer\-v/data/:/data/\-w/root/xfastertransformer\-e"http_proxy=$http_proxy"\-e"https_proxy=$https_proxy"\intel/xfastertransformer:dev-ubuntu22.04Notice!!!: Please enlarge--shm-sizeifbus erroroccurred while running in the multi-ranks mode . The default docker limits the shared memory size to 64MB and our implementation uses many shared memories to achieve a  better performance.How to buildUsing 'CMake'# Build xFasterTransformergitclonehttps://github.com/intel/xFasterTransformer.gitxFasterTransformercdxFasterTransformer
gitcheckout<latest-tag># Please make sure torch is installed when run python examplemkdirbuild&&cdbuild
cmake..
make-jUsingpython setup.py# Build xFasterTransformer library and C++ example.pythonsetup.pybuild# Install xFasterTransformer into pip environment.# Notice: Run `python setup.py build` before installation!pythonsetup.pyinstallModels PreparationxFasterTransformer supports a different model format from Huggingface, but it's compatible with FasterTransformer's format.Download the huggingface format model firstly.After that, convert the model into xFasterTransformer format by using model convert module in xfastertransformer. If output directory is not provided, converted model will be placed into${HF_DATASET_DIR}-xft.python -c 'import xfastertransformer as xft; xft.LlamaConvert().convert("${HF_DATASET_DIR}","${OUTPUT_DIR}")'Supported model convert list:LlamaConvertChatGLMConvertChatGLM2ConvertChatGLM3ConvertOPTConvertBaichuanConvertQwenConvertAPI usageFor more details, please see API document andexamples.Python API(PyTorch)Firstly, please install the dependencies.Python dependenciespipinstall-rrequirements.txtoneCCL (For multi ranks)Install oneCCL and setup the environment. Please refer toPrepare Environment.xFasterTransformer's Python API is similar to transformers and also supports transformers's streamer to achieve the streaming output. In the example, we use transformers to encode input prompts to token ids.importxfastertransformerfromtransformersimportAutoTokenizer,TextStreamer# Assume huggingface model dir is `/data/chatglm-6b-hf` and converted model dir is `/data/chatglm-6b-xft`.MODEL_PATH="/data/chatglm-6b-xft"TOKEN_PATH="/data/chatglm-6b-hf"INPUT_PROMPT="Once upon a time, there existed a little girl who liked to have adventures."tokenizer=AutoTokenizer.from_pretrained(TOKEN_PATH,use_fast=False,padding_side="left",trust_remote_code=True)streamer=TextStreamer(tokenizer,skip_special_tokens=True,skip_prompt=False)input_ids=tokenizer(INPUT_PROMPT,return_tensors="pt",padding=False).input_idsmodel=xfastertransformer.AutoModel.from_pretrained(MODEL_PATH,dtype="bf16")generated_ids=model.generate(input_ids,max_length=200,streamer=streamer)C++ APISentencePiececan be used to tokenizer and detokenizer text.#include<vector>#include<iostream>#include"xfastertransformer.h"// ChatGLM token ids for prompt "Once upon a time, there existed a little girl who liked to have adventures."std::vector<int>input({3393,955,104,163,6,173,9166,104,486,2511,172,7599,103,127,17163,7,130001,130004});// Assume converted model dir is `/data/chatglm-6b-xft`.xft::AutoModelmodel("/data/chatglm-6b-xft",xft::DataType::bf16);model.config(/*max length*/100,/*num beams*/1);model.input(/*input token ids*/input,/*batch size*/1);while(!model.isDone()){std::vector<int>nextIds=model.generate();}std::vector<int>result=model.finalize();for(autoid:result){std::cout<<id<<" ";}std::cout<<std::endl;How to runRecommend preloadinglibiomp5.soto get a better performance.libiomp5.sofile will be in3rdparty/mklml/libdirectory after building xFasterTransformer successfully.Single rankFasterTransformer will automatically check the MPI environment, or you can use theSINGLE_INSTANCE=1environment variable to forcefully deactivate MPI.Multi ranksCommand lineUse MPI to run in the multi-ranks mode, please install oneCCL firstly.oneCCL InstallationIf you have built xfastertransformer from source, oneCCL is installed in 3rdparty when compilation.source ./3rdparty/oneccl/build/_install/env/setvars.sh[Recommended]Use provided scripts to build it from source code.cd3rdparty
shprepare_oneccl.shsource./oneccl/build/_install/env/setvars.shInstall oneCCL through installingIntel® oneAPI Base Toolkit.(Notice:It is recommended to use versions 2023.x and below.)And source the enviroment by:source /opt/intel/oneapi/setvars.shHere is a example on local.OMP_NUM_THREADS=48LD_PRELOAD=libiomp5.sompirun\-n1numactl-N0-m0${RUN_WORKLOAD}:\-n1numactl-N1-m1${RUN_WORKLOAD}CodeFor more details, please refer to examples.Pythonmodel.rankcan get the process's rank,model.rank == 0is the Master.For Slaves, after loading the model, the only thing needs to do ismodel.generate(). The input and generation configuration will be auto synced.model=xfastertransformer.AutoModel.from_pretrained("/data/chatglm-6b-xft",dtype="bf16")# SlavewhileTrue:model.generate()C++model.getRank()can get the process's rank,model.getRank() == 0is the Master.For Slaves, any value can be input tomodel.config()andmodel.inputsince Master's value will be synced.xft::AutoModelmodel("/data/chatglm-6b-xft",xft::DataType::bf16);// Slavewhile(1){model.config();std::vector<int>input_ids;model.input(/*input token ids*/input_ids,/*batch size*/1);while(!model.isDone()){model.generate();}}Web DemoA web demo based onGradiois provided in repo. Now support ChatGLM, ChatGLM2 and Llama2 models.Perpare the model.Install the dependenciespipinstall-rexamples/web_demo/requirements.txtRun the script corresponding to the model. After the web server started, open the output URL in the browser to use the demo. Please specify the paths of model and tokenizer directory, and data type.transformer's tokenizer is used to encode and decode text so${TOKEN_PATH}means the huggingface model directory. This demo also support multi-rank.# Recommend preloading `libiomp5.so` to get a better performance.# `libiomp5.so` file will be in `3rdparty/mklml/lib` directory after build xFasterTransformer.LD_PRELOAD=libiomp5.sopythonexamples/web_demo/ChatGLM.py\--dtype=bf16\--token_path=${TOKEN_PATH}\--model_path=${MODEL_PATH}BenchmarkBenchmark scripts are provided to get the model inference performance quickly.Prepare the model.Install the dependencies, including oneCCL and python dependencies.Enter thebenchmarkfolder and runrun_benchmark.sh. Please refer toBenchmark READMEfor more information.Notes!!!: The system and CPU configuration may be different. For the best performance, please try to modify OMP_NUM_THREADS, datatype and the memory nodes number (check the memory nodes usingnumactl -H) according to your test environment.SupportxFasterTransformer email:xft.maintainer@intel.comxFasterTransformerwechatQ&AQ: Can xFasterTransformer run on a Intel® Core™ CPU?A: No. xFasterTransformer requires support for the AMX and AVX512 instruction sets, which are not available on Intel® Core™ CPUs.Q: Can xFasterTransformer run on the Windows system?A: There is no native support for Windows, and all compatibility tests are only conducted on Linux, so Linux is recommended.Q: Why does the program freeze or exit with errors when running in multi-rank mode after installing the latest version of oneCCL through oneAPI?A: Please try downgrading oneAPI to version 2023.x or below, or use the provided script to install oneCCL from source code.Q: Why does running the program using two CPU sockets result in much lower performance compared to running on a single CPU socket?A: Running in this way causes the program to engage in many unnecessary cross-socket communications, significantly impacting performance. If there is a need for cross-socket deployment, consider running in a multi-rank mode with one rank on each socket.Q:The performance is normal when running in a single rank, but why is the performance very slow and the CPU utilization very low when using MPI to run multiple ranks?A:This is because the program launched through MPI readsOMP_NUM_THREADS=1, which cannot correctly retrieve the appropriate value from the environment. It is necessary to manually set the value ofOMP_NUM_THREADSbased on the actual situation.Q: Why do I still encounter errors when converting already supported models?A: Try downgradingtransformerto an appropriate version, such as the version specified in therequirements.txt. This is because different versions of Transformer may change the names of certain variables.