diff --git a/README.md b/README.md index 154df8298fab5ecf322016157858e08cd1bccbe1..7aba311942eb9ef66059638f840227a34d6d9ffa 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,257 @@ ---- -license: apache-2.0 ---- +# Qwen1.5 + +

+ +

+ +

+ 🤗 Hugging Face   |   🤖 ModelScope   |    📑 Blog    |   📖 Documentation +
+🖥️ Demo   |   💬 WeChat (微信)   |   🫨 Discord   +

+ + +Visit our Hugging Face or ModelScope organization (click links above), search checkpoints with names starting with `Qwen1.5-`, and you will find all you need! Enjoy! + + + +## Introduction +This time, we upgrade Qwen to Qwen1.5, the beta version of Qwen2. Similar to Qwen, it is still a decoder-only transformer model with SwiGLU activation, RoPE, multi-head attention. At this moment, we have achieved: +* 6 model sizes: 0.5B, 1.8B, 4B, 7B, 14B, and 72B; +* Significant model quality improvements in chat models; +* Strengthened multilingual capabilities in both base and chat models; +* All models support the context length of `32768` tokens; +* System prompts enabled for all models, which means roleplay is possible. +* No need of `trust_remote_code` anymore. + +We have not integrated GQA and mixture of SWA and full attention in this version and we will add the features in the future version. + + +## News +* 2024.02.05: We released the Qwen1.5 series. + +## Performance +Detailed evaluation results are reported in this 📑 blog. + + +## Requirements +* `transformers>=4.37.0`. + +> [!Warning] +>
+> +> 🚨 This is a must because `transformers` integrated Qwen2 codes since `4.37.0`. +> +>
+ +## Quickstart + +### 🤗 Hugging Face Transformers + +Here we show a code snippet to show you how to use the chat model with `transformers`: + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer +device = "cuda" # the device to load the model onto + +model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen1.5-72B-Chat", + torch_dtype="auto", + device_map="auto" +) +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-72B-Chat") + +prompt = "Give me a short introduction to large language model." +messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": prompt} +] +text = tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True +) +model_inputs = tokenizer([text], return_tensors="pt").to(device) + +generated_ids = model.generate( + model_inputs.input_ids, + max_new_tokens=512 +) +generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) +] + +response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +``` + +For quantized models, we advise you to use the GPTQ and AWQ correspondents, namely `Qwen1.5-7B-Chat-GPTQ-Int8`, `Qwen1.5-7B-Chat-AWQ`. + +### 🤖 ModelScope +We strongly advise users especially those in mainland China to use ModelScope. `snapshot_download` can help you solve issues concerning downloading checkpoints. + +### 💻 Run locally + +#### Ollama + +> [!NOTE] +>
+> Ollama provides an OpenAI-compatible API, which however does NOT support function calling. For tool use capabilities, consider using Qwen-Agent, which offers a wrapper for function calling over the API. +>
+ +After [installing ollama](https://github.com/ollama/ollama/blob/main/README.md), you can initiate the ollama service with the following command: +```shell +ollama serve +# You need to keep this service running whenever you are using ollama +``` + +To pull a model checkpoint and run the model, use the `ollama run` command. You can specify a model size by adding a suffix to `qwen`, such as `:0.5b`, `:1.8b`, `:4b`, `:7b`, `:14b`, or `:72b`: +```shell +ollama run qwen:4b +# To exit, type "/bye" and press ENTER +``` + +You can also access the ollama service via its OpenAI-compatible API. Please note that you need to (1) keep `ollama serve` running while using the API, and (2) execute `ollama run qwen:4b` before utilizing this API to ensure that the model checkpoint is prepared. +```py +from openai import OpenAI +client = OpenAI( + base_url='http://localhost:11434/v1/', + api_key='ollama', # required but ignored +) +chat_completion = client.chat.completions.create( + messages=[ + { + 'role': 'user', + 'content': 'Say this is a test', + } + ], + model='qwen:4b', +) +``` + +For additional details, please visit [ollama.ai](https://ollama.ai/). + +#### llama.cpp +Download our provided GGUF files or create them by yourself, and you can directly use them with the latest [`llama.cpp`](https://github.com/ggerganov/llama.cpp) with a one-line command: +```shell +./main -m -n 512 --color -i -cml -f prompts/chat-with-qwen.txt +``` + +#### LMStudio +Qwen1.5 has already been supported by [lmstudio.ai](https://lmstudio.ai/). You can directly use LMStudio with our GGUF files. + +#### OpenVINO +Qwen1.5 has already been supported by [OpenVINO toolkit](https://github.com/openvinotoolkit). You can install and run this [example notebook](https://github.com/openvinotoolkit/openvino_notebooks/tree/main/notebooks/254-llm-chatbot) with Intel CPU, integrated GPU or discrete GPU. + + +## Web UI + +#### Text generation web UI +You can directly use [`text-generation-webui`](https://github.com/oobabooga/text-generation-webui) for creating a web UI demo. If you use GGUF, remember to install the latest wheel of `llama.cpp` with the support of Qwen1.5. + + +#### llamafile +Clone [`llamafile`](https://github.com/Mozilla-Ocho/llamafile), run source install, and then create your own llamafile with the GGUF file following the guide [here](https://github.com/Mozilla-Ocho/llamafile?tab=readme-ov-file#creating-llamafiles). You are able to run one line of command, say `./qwen.llamafile`, to create a demo. + + +## Deployment +Now, Qwen1.5 is supported by multiple inference frameworks. Here we demonstrate the usage of `vLLM` and `SGLang`. + +> [!Warning] +>
+> The OpenAI-compatible APIs provided by vLLM and SGLang currently do NOT support function calling. For tool use capabilities, Qwen-Agent provides a wrapper around these APIs to support function calling. +>
+ +### vLLM +We advise you to use `vLLM>=0.3.0` to build OpenAI-compatible API service. Start the server with a chat model, e.g. `Qwen1.5-7B-Chat`: +```shell +python -m vllm.entrypoints.openai.api_server --served-model-name Qwen1.5-7B-Chat --model Qwen/Qwen1.5-7B-Chat +``` + +Then use the chat API as demonstrated below: + +```shell +curl http://localhost:8000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "Qwen1.5-7B-Chat", + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."} + ] + }' +``` +```python +from openai import OpenAI +# Set OpenAI's API key and API base to use vLLM's API server. +openai_api_key = "EMPTY" +openai_api_base = "http://localhost:8000/v1" + +client = OpenAI( + api_key=openai_api_key, + base_url=openai_api_base, +) + +chat_response = client.chat.completions.create( + model="Qwen1.5-7B-Chat", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."}, + ] +) +print("Chat response:", chat_response) +``` + +### SGLang +Please install `SGLang` from source. Similar to `vLLM`, you need to launch a server and use OpenAI-compatible API service. Start the server first: +```shell +python -m sglang.launch_server --model-path Qwen/Qwen1.5-7B-Chat --port 30000 +``` +You can use it in Python as shown below: +```python +from sglang import function, system, user, assistant, gen, set_default_backend, RuntimeEndpoint + +@function +def multi_turn_question(s, question_1, question_2): + s += system("You are a helpful assistant.") + s += user(question_1) + s += assistant(gen("answer_1", max_tokens=256)) + s += user(question_2) + s += assistant(gen("answer_2", max_tokens=256)) + +set_default_backend(RuntimeEndpoint("http://localhost:30000")) + +state = multi_turn_question.run( + question_1="What is the capital of China?", + question_2="List two local attractions.", +) + +for m in state.messages(): + print(m["role"], ":", m["content"]) + +print(state["answer_1"]) +``` + +## Finetuning +We advise you to use training frameworks, including [Axolotl](https://github.com/OpenAccess-AI-Collective/axolotl), [Llama-Factory](https://github.com/hiyouga/LLaMA-Factory), [Swift](https://github.com/modelscope/swift), etc., to finetune your models with SFT, DPO, PPO, etc. + +## API +Qwen1.5 models are now deployed on both [DashScope](https://dashscope.aliyun.com/) and [Together](https://api.together.ai/). Check [this](https://api.together.xyz/playground/chat/Qwen/Qwen1.5-72B-Chat) out and have fun with Qwen1.5-72B-Chat! + +## License Agreement +Check the license of each model inside its HF repo. It is NOT necessary for you to submit a request for commercial usage. + +## Citation +If you find our work helpful, feel free to give us a cite. + +``` +@article{qwen, + title={Qwen Technical Report}, + author={Jinze Bai and Shuai Bai and Yunfei Chu and Zeyu Cui and Kai Dang and Xiaodong Deng and Yang Fan and Wenbin Ge and Yu Han and Fei Huang and Binyuan Hui and Luo Ji and Mei Li and Junyang Lin and Runji Lin and Dayiheng Liu and Gao Liu and Chengqiang Lu and Keming Lu and Jianxin Ma and Rui Men and Xingzhang Ren and Xuancheng Ren and Chuanqi Tan and Sinan Tan and Jianhong Tu and Peng Wang and Shijie Wang and Wei Wang and Shengguang Wu and Benfeng Xu and Jin Xu and An Yang and Hao Yang and Jian Yang and Shusheng Yang and Yang Yao and Bowen Yu and Hongyi Yuan and Zheng Yuan and Jianwei Zhang and Xingxuan Zhang and Yichang Zhang and Zhenru Zhang and Chang Zhou and Jingren Zhou and Xiaohuan Zhou and Tianhang Zhu}, + journal={arXiv preprint arXiv:2309.16609}, + year={2023} +} +``` + +## Contact Us +If you are interested to leave a message to either our research team or product team, join our [Discord](https://discord.gg/z3GAxXZ9Ce) or [WeChat groups](assets/wechat.png)! + diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..269cadcf83e9817fe95f9770e2f774fab7057542 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/locales/zh_CN/LC_MESSAGES/deployment/vllm.mo b/docs/locales/zh_CN/LC_MESSAGES/deployment/vllm.mo new file mode 100644 index 0000000000000000000000000000000000000000..163d85f261478282796608e495ae0830fc4b7211 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/deployment/vllm.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/deployment/vllm.po b/docs/locales/zh_CN/LC_MESSAGES/deployment/vllm.po new file mode 100644 index 0000000000000000000000000000000000000000..f5bc496d00e5213791514d890b2d5ac4c402c1a7 --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/deployment/vllm.po @@ -0,0 +1,159 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/deployment/vllm.rst:2 c78a51ede5ef46d182efb0495820be10 +msgid "vLLM" +msgstr "vLLM" + +#: ../../source/deployment/vllm.rst:4 39eba3f4176443e3bea91397e9ede435 +msgid "" +"We recommend you trying with `vLLM `__ for your deployement of Qwen. It is simple to use, and " +"it is fast with state-of-the-art serving throughtput, efficienct " +"management of attention key value memory with PagedAttention, continuous " +"batching of input requests, optimized CUDA kernels, etc. To learn more " +"about vLLM, please refer to the `paper " +"`__ and `documentation " +"`__." +msgstr "我们建议您在部署Qwen时尝试使用 `vLLM `__ 。它易于使用,且具有最先进的服务吞吐量、高效的注意力键值内存管理(通过PagedAttention实现)、连续批处理输入请求、优化的CUDA内核等功能。要了解更多关于vLLM的信息,请参阅 `论文 `__ 和 `文档 `__ 。" + +#: ../../source/deployment/vllm.rst:14 824e70bf8dff4879bbb0eb51c038b6d6 +msgid "Installation" +msgstr "安装" + +#: ../../source/deployment/vllm.rst:16 5f1f51379ca84bb7a5b5362b7e7d9e82 +msgid "" +"By default, you can install ``vLLM`` by pip: ``pip install vLLM>=0.3.0``," +" but if you are using CUDA 11.8, check the note in the official document " +"for installation (`link " +"`__) " +"for some help. We also advise you to install ray by ``pip install ray`` " +"for distributed serving." +msgstr "默认情况下,你可以通过 ``pip`` 来安装vLLM :``pip install vLLM>=0.3.0`` , 但如果你正在使用 CUDA 11.8,请查看官方文档中的注意事项 以获取有关安装的帮助( `链接 `__ )。 我们也建议你通过 ``pip install ray`` 安装ray, 以便支持分布式服务。" + +#: ../../source/deployment/vllm.rst:24 b7cda8f24f53482b89940ec7ea1b747f +msgid "Offline Batched Inference" +msgstr "离线推理" + +#: ../../source/deployment/vllm.rst:26 2aeda0988c284b4083e64fb11ac48472 +msgid "" +"Models supported by Qwen2 codes, e.g., Qwen1.5, are supported by vLLM. " +"The simplest usage of vLLM is offline batched inference as demonstrated " +"below." +msgstr "Qwen2代码支持的模型,例如Qwen1.5,都被vLLM所支持。 vLLM最简单的使用方式是通过以下演示进行离线批量推理。" + +#: ../../source/deployment/vllm.rst:63 f79753fdb5aa4b0686e2457925ed83ba +msgid "OpenAI-API Compatible API Service" +msgstr "适配OpenAI-API的API服务" + +#: ../../source/deployment/vllm.rst:65 8418e661aa044763b45a114d6231ca12 +msgid "" +"It is easy to build an OpenAI-API compatible API service with vLLM, which" +" can be deployed as a server that implements OpenAI API protocol. By " +"default, it starts the server at ``http://localhost:8000``. You can " +"specify the address with ``--host`` and ``--port`` arguments. Run the " +"command as shown below:" +msgstr "借助vLLM,构建一个与OpenAI API兼容的API服务十分简便,该服务可以作为实现OpenAI API协议的服务器进行部署。默认情况下,它将在 `http://localhost:8000 `__ 启动服务器。您可以通过 ``--host`` 和 ``--port`` 参数来自定义地址。请按照以下所示运行命令:" + +#: ../../source/deployment/vllm.rst:76 671f946fbe424b2086e1dcce4df7d156 +msgid "" +"You don’t need to worry about chat template as it by default uses the " +"chat template provided by the tokenizer." +msgstr "你无需担心chat模板,因为它默认会使用由tokenizer提供的chat模板。" + +#: ../../source/deployment/vllm.rst:79 9ac8c5901cae46d0b406fdd7f2da6feb +msgid "" +"Then, you can use the `create chat interface " +"`__ to communicate with Qwen:" +msgstr "然后,您可以利用 `create chat interface `__ 来与Qwen进行对话:" + +#: ../../source/deployment/vllm.rst:93 72eaebe10a8d4769a9ce15f68f5aaef5 +msgid "" +"or you can use python client with ``openai`` python package as shown " +"below:" +msgstr "或者您可以如下面所示使用 ``openai`` Python 包中的 Python 客户端:" + +#: ../../source/deployment/vllm.rst:118 3d91f5241559497b92f1215723526ce5 +msgid "Multi-GPU Distributred Serving" +msgstr "多卡分布式部署" + +#: ../../source/deployment/vllm.rst:120 de0f6109c6c54ec498dad7572dbc03bb +msgid "" +"To scale up your serving throughputs, distributed serving helps you by " +"leveraging more GPU devices. Besides, for large models like ``Qwen1.5" +"-72B-Chat``, it is impossible to serve it on a single GPU. Here, we " +"demonstrate how to run ``Qwen1.5-72B-Chat`` with tensor parallelism just " +"by passing in the argument ``tensor_parallel_size``:" +msgstr "要提高模型的处理吞吐量,分布式服务可以通过利用更多的GPU设备来帮助您。特别是对于像 ``Qwen1.5-72B-Chat`` 这样的大模型,单个GPU无法支撑其在线服务。在这里,我们通过演示如何仅通过传入参数 ``tensor_parallel_size`` ,来使用张量并行来运行 ``Qwen1.5-72B-Chat`` 模型:" + +#: ../../source/deployment/vllm.rst:131 8a8342a0388e4e6e9af7e67d1b664049 +msgid "" +"You can run multi-GPU serving by passing in the argument ``--tensor-" +"parallel-size``:" +msgstr "您可以通过传递参数 ``--tensor-parallel-size`` 来运行多GPU服务:" + +#: ../../source/deployment/vllm.rst:141 1b322fc6beda485d85073871e8d79009 +msgid "Serving Quantized Models" +msgstr "部署量化模型" + +#: ../../source/deployment/vllm.rst:143 f78f39a1d50e428b8f9a46880afc33db +msgid "" +"vLLM supports different types of quantized models, including AWQ, GPTQ, " +"SqueezeLLM, etc. Here we show how to deploy AWQ and GPTQ models. The " +"usage is almost the same as above except for an additional argument for " +"quantization. For example, to run an AWQ model. e.g., ``Qwen1.5-7B-Chat-" +"AWQ``:" +msgstr "vLLM 支持多种类型的量化模型,例如 AWQ、GPTQ、SqueezeLLM 等。这里我们将展示如何部署 AWQ 和 GPTQ 模型。使用方法与上述基本相同,只不过需要额外指定一个量化参数。例如,要运行一个 AWQ 模型,例如 ``Qwen1.5-7B-Chat-AWQ`` :" + +#: ../../source/deployment/vllm.rst:154 828cb96a6d4543aba4145552c9b0c5b2 +msgid "or GPTQ models like ``Qwen1.5-7B-Chat-GPTQ-Int8``:" +msgstr "或者是GPTQ模型比如 ``Qwen1.5-7B-Chat-GPTQ-Int8`` :" + +#: ../../source/deployment/vllm.rst:160 7869bd5c2bb542f393215ab5f85315f3 +msgid "" +"Similarly, you can run serving adding the argument ``--quantization`` as " +"shown below:" +msgstr "同样地,您可以在运行服务时添加 ``--quantization`` 参数,如下所示:" + +#: ../../source/deployment/vllm.rst:169 dca42b48bef043cf81c89efa5ed2663c +msgid "or" +msgstr "或者" + +#: ../../source/deployment/vllm.rst:177 27cc85ab1f474328bbd863413ba83883 +msgid "" +"Additionally, vLLM supports the combination of AWQ or GPTQ models with KV" +" cache quantization, namely FP8 E5M2 KV Cache. For example:" +msgstr "此外,vLLM支持将AWQ或GPTQ模型与KV缓存量化相结合,即FP8 E5M2 KV Cache方案。例如:" + +#: ../../source/deployment/vllm.rst:192 fa4a78593b0347d89685a3317e382560 +msgid "Troubleshooting" +msgstr "常见问题" + +#: ../../source/deployment/vllm.rst:194 303b60dd7fa14134aa8bc2db5d2d2a19 +msgid "" +"You may encounter OOM issues that are pretty annoying. We recommend two " +"arguments for you to make some fix. The first one is ``--max-model-len``." +" Our provided default ``max_postiion_embedding`` is ``32768`` and thus " +"the maximum length for the serving is also this value, leading to higher " +"requirements of memory. Reducing it to a proper length for yourself often" +" helps with the OOM issue. Another argument you can pay attention to is " +"``--gpu-memory-utilization``. By default it is ``0.9`` and you can level " +"it up to tackle the OOM problem. This is also why you find a vLLM service" +" always takes so much memory." +msgstr "您可能会遇到令人烦恼的OOM(内存溢出)问题。我们推荐您尝试两个参数进行修复。第一个参数是 ``--max-model-len`` 。我们提供的默认最大位置嵌入(max_position_embedding)为32768,因此服务时的最大长度也是这个值,这会导致更高的内存需求。将此值适当减小通常有助于解决OOM问题。另一个您可以关注的参数是 ``--gpu-memory-utilization`` 。默认情况下,该值为 ``0.9`` ,您可以将其调高以应对OOM问题。这也是为什么您发现一个大型语言模型服务总是占用大量内存的原因。" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/getting_started/installation.mo b/docs/locales/zh_CN/LC_MESSAGES/getting_started/installation.mo new file mode 100644 index 0000000000000000000000000000000000000000..da60daaaa0d245b38feb74d6a4b20b754387a143 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/getting_started/installation.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/getting_started/installation.po b/docs/locales/zh_CN/LC_MESSAGES/getting_started/installation.po new file mode 100644 index 0000000000000000000000000000000000000000..880fb0b418df794205b908fef5fa6e481337816a --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/getting_started/installation.po @@ -0,0 +1,47 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/getting_started/installation.rst:2 +#: deb8f437f6fa43f58a37268ecf29e339 +msgid "Installation" +msgstr "安装" + +#: ../../source/getting_started/installation.rst:4 +#: 522d89ca22b3435382fbb514205c2dcd +msgid "" +"To get a quick start with Qwen1.5, you can install the ``transformers`` " +"library from Hugging Face and use models in the `Qwen1.5 collection " +"`__." +" We advise you to install the latest ``transformers`` or at least version" +" 4.37.0." +msgstr "要快速上手Qwen1.5,您可以从Hugging Face安装 ``transformers`` 库,并使用 `Qwen1.5 Collection `__ 中的模型。我们建议您安装最新版本的 ``transformers`` 库,或者至少安装4.37.0版本。" + +#: ../../source/getting_started/installation.rst:11 +#: 514b20d297d345ebaaf16381b6ce1d4e +msgid "Install with Pip" +msgstr "Pip安装" + +#: ../../source/getting_started/installation.rst:18 +#: 892ae185130049779862b4b91425d9de +msgid "Install with Conda" +msgstr "Conda安装" + +#: ../../source/getting_started/installation.rst:24 +#: a7db48bd0a4f49e3b24a7a44cca4defd +msgid "We advise you to use Python 3.8 or higher, and Pytorch 2.0 or higher." +msgstr "我们建议您使用Python3.8及以上版本和Pytorch 2.0及以上版本。" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/getting_started/quickstart.mo b/docs/locales/zh_CN/LC_MESSAGES/getting_started/quickstart.mo new file mode 100644 index 0000000000000000000000000000000000000000..2de20abebdc474448864dd8579f92c470f3bb3e6 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/getting_started/quickstart.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/getting_started/quickstart.po b/docs/locales/zh_CN/LC_MESSAGES/getting_started/quickstart.po new file mode 100644 index 0000000000000000000000000000000000000000..a6f49a1465c11db5d5db3df8ad7d7718ad781f47 --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/getting_started/quickstart.po @@ -0,0 +1,121 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/getting_started/quickstart.rst:2 +#: 0d59f700095e438687bc5ef12625a233 +msgid "Quickstart" +msgstr "快速开始" + +#: ../../source/getting_started/quickstart.rst:4 +#: 34c301da60d148e391e99560081c476f +msgid "" +"This guide helps you quickly start using Qwen1.5. We provide examples of " +"`Hugging Face Transformers " +"`__ as well as `ModelScope " +"`__, and `vLLM " +"`__ for deployment." +msgstr "本指南帮助您快速上手Qwen1.5的使用,并提供了如下示例: `Hugging Face Transformers `__ 以及 `ModelScope `__ 和 `vLLM `__ 在部署时的应用实例。" + +#: ../../source/getting_started/quickstart.rst:10 +#: 4a4d501b6a8243348c451132208ff369 +msgid "Hugging Face Transformers & ModelScope" +msgstr "Hugging Face Transformers & ModelScope" + +#: ../../source/getting_started/quickstart.rst:12 +#: 73463ba21bec4384bd2db9e3deb03ec9 +msgid "" +"To get a quick start with Qwen1.5, we advise you to try with the " +"inference with ``transformers`` first. Make sure that you have installed " +"``transformers>=4.37.0``. The following is a very simple code snippet " +"showing how to run Qwen1.5-Chat, with an example of Qwen1.5-7B-Chat:" +msgstr "要快速上手Qwen1.5,我们建议您首先尝试使用transformers进行推理。请确保已安装了 ``transformers>=4.37.0`` 版本。以下是一个非常简单的代码片段示例,展示如何运行Qwen1.5-Chat模型,其中包含 ``Qwen1.5-7B-Chat`` 的实例:" + +#: ../../source/getting_started/quickstart.rst:56 +#: 02d8873c2f4944bd8e555b1a7ca0bd83 +msgid "" +"Previously, we use ``model.chat()`` (see ``modeling_qwen.py`` in previous" +" Qwen models for more information). Now, we follow the practice of " +"``transformers`` and directly use ``model.generate()`` with " +"``apply_chat_template()`` in tokenizer." +msgstr "以前,我们使用 ``model.chat()`` (有关更多详细信息,请参阅先前Qwen模型中的 ``modeling_qwen.py`` )。现在,我们遵循 ``transformers`` 的实践,直接使用 ``model.generate()`` 配合tokenizer中的 ``apply_chat_template()`` 方法。" + +#: ../../source/getting_started/quickstart.rst:61 +#: 69a7184639c842a3b3036eb4ed564746 +msgid "" +"To tackle with downloading issues, we advise you to try with from " +"ModelScope, just changing the first line of code above to the following:" +msgstr "为了解决下载问题,我们建议您尝试从 ModelScope 进行下载,只需将上述代码的第一行更改为以下内容:" + +#: ../../source/getting_started/quickstart.rst:68 +#: 74ec66c1e58444509705de8097aa3f93 +msgid "" +"Streaming mode for model chat is simple with the help of " +"``TextStreamer``. Below we show you an example of how to use it:" +msgstr "借助 ``TextStreamer`` ,chat的流式模式变得非常简单。下面我们将展示一个如何使用它的示例:" + +#: ../../source/getting_started/quickstart.rst:84 +#: fedfd60540414413ba87cdc77dde4f3a +msgid "vLLM for Deployment" +msgstr "使用vLLM部署" + +#: ../../source/getting_started/quickstart.rst:86 +#: 0306956b41b04d2a9c349942abd29743 +msgid "" +"To deploy Qwen1.5, we advise you to use vLLM. vLLM is a fast and easy-to-" +"use framework for LLM inference and serving. In the following, we " +"demonstrate how to build a OpenAI-API compatible API service with vLLM." +msgstr "要部署Qwen1.5,我们建议您使用vLLM。vLLM是一个用于LLM推理和服务的快速且易于使用的框架。以下,我们将展示如何使用vLLM构建一个与OpenAI API兼容的API服务。" + +#: ../../source/getting_started/quickstart.rst:91 +#: ea047884429444f69cf13fa20a9a1226 +msgid "First, make sure you have installed ``vLLM>=0.3.0``:" +msgstr "首先,确保你已经安装 ``vLLM>=0.3.0`` :" + +#: ../../source/getting_started/quickstart.rst:97 +#: fa3653a7e100405a9150d61cbc7aa0bf +msgid "" +"Run the following code to build up a vllm service. Here we take Qwen1.5" +"-7B-Chat as an example:" +msgstr "运行以下代码以构建vllm服务。此处我们以Qwen1.5-7B-Chat为例:" + +#: ../../source/getting_started/quickstart.rst:104 +#: 3ca1e2527a2f4f359ca353cf02e394c5 +msgid "" +"Then, you can use the `create chat interface " +"`__ to communicate with Qwen:" +msgstr "然后,您可以使用 `create chat interface `__ 来与Qwen进行交流:" + +#: ../../source/getting_started/quickstart.rst:118 +#: 903bf1697ebc472fa96655cd6eefaf94 +msgid "" +"or you can use python client with ``openai`` python package as shown " +"below:" +msgstr "或者您可以按照下面所示的方式,使用 ``openai`` Python 包中的Python 客户端:" + +#: ../../source/getting_started/quickstart.rst:143 +#: 930fecfab8b64a33ab1807427ca1ffe9 +msgid "Next Step" +msgstr "下一步" + +#: ../../source/getting_started/quickstart.rst:145 +#: dc8967f0befe41f781a22ada80e0a361 +msgid "" +"Now, you can have fun with Qwen models. Would love to know more about its" +" usages? Feel free to check other documents in this documentation." +msgstr "现在,您可以尽情探索Qwen模型的各种用途。若想了解更多,请随时查阅本文档中的其他内容。" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/index.mo b/docs/locales/zh_CN/LC_MESSAGES/index.mo new file mode 100644 index 0000000000000000000000000000000000000000..4bdd7924e082ffda1f6e6fa509bb935764ffb21a Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/index.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/index.po b/docs/locales/zh_CN/LC_MESSAGES/index.po new file mode 100644 index 0000000000000000000000000000000000000000..648c01cbb0ccf7a9d76efbd85153962d4b96d389 --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/index.po @@ -0,0 +1,138 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-03-04 15:21+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language: zh_CN\n" +"Language-Team: zh_CN \n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/index.rst:42 +msgid "Getting Started" +msgstr "快速开始" + +#: ../../source/index.rst:49 +msgid "Inference" +msgstr "推理" + +#: ../../source/index.rst:55 +msgid "Run Locally" +msgstr "本地运行" + +#: ../../source/index.rst:62 +msgid "Web UI" +msgstr "Web UI" + +#: ../../source/index.rst:68 +msgid "Quantization" +msgstr "量化" + +#: ../../source/index.rst:76 +msgid "Deployment" +msgstr "部署" + +#: ../../source/index.rst:82 +msgid "Training" +msgstr "训练" + +#: ../../source/index.rst:7 2d3747ef5e9a463ebdd4f47fa4fd614b +msgid "Welcome to Qwen!" +msgstr "欢迎来到Qwen" + +#: ../../source/index.rst:-1 261ac6a5ed984af08f173e4e317239f0 +msgid "Qwen" +msgstr "" + +#: ../../source/index.rst:16 a75ccce7dbae42528044bd349bec2406 +#, fuzzy +msgid "" +"Qwen is the large language model and large multimodal model series of the" +" Qwen Team, Alibaba Group. Now the large language models have been " +"upgraded to Qwen1.5. Both language models and multimodal models are " +"pretrained on large-scale multilingual and multimodal data and post-" +"trained on quality data for aligning to human preferences. Qwen is " +"capable of natural language understanding, text generation, vision " +"understanding, audio understanding, tool use, role play, playing as AI " +"agent, etc." +msgstr "" +"Qwen是阿里巴巴集团Qwen团队研发的大语言模型和大型多模态模型系列。目前,大语言模型已升级至Qwen1.5版本。无论是语言模型还是多模态模型,均在大规模多语言和多模态数据上进行预训练,并通过高质量数据进行后期微调以贴近人类偏好。Qwen具备自然语言理解、文本生成、视觉理解、音频理解、工具使用、角色扮演、作为AI" +" Agent进行互动等多种能力。" + +#: ../../source/index.rst:19 3491cf32758549fb9178f7f6ec74c568 +msgid "The latest version, Qwen1.5, has the following features:" +msgstr "最新版本Qwen1.5有以下特点:" + +#: ../../source/index.rst:21 31a2e69fd9894077b1121a7112b219a2 +msgid "6 model sizes, including 0.5B, 1.8B, 4B, 7B, 14B, and 72B;" +msgstr "6种模型规模,包括0.5B、1.8B、4B、7B、14B和72B;" + +#: ../../source/index.rst:22 eb837bd71db8400792a68d6ca470ac3a +msgid "" +"Base and chat models for each size, with the chat models aligned for " +"human preferences;" +msgstr "针对每种尺寸提供基础模型和Chat模型,并确保聊天模型按照人类偏好进行校准;" + +#: ../../source/index.rst:23 0d1bfd621aac4df6a53213d90492c39b +msgid "Multilingual support of both base and chat models;" +msgstr "对基础模型和Chat模型的多语言支持" + +#: ../../source/index.rst:24 7ff10a8a6e724630b7a92d32c84566d3 +msgid "Stable support of 32K context length for models of all sizes" +msgstr "基础模型和聊天模型都支持多种语言;" + +#: ../../source/index.rst:25 9ab7e4b426d445a0bd59a7560ec98475 +msgid "Supporting tool use, RAG, role play, and playing as AI agent;" +msgstr "支持工具调用、RAG(检索增强文本生成)、角色扮演、AI Agent等;" + +#: ../../source/index.rst:27 c6fc5c5e004644daba19e91be5da82cc +msgid "For more information, please visit our:" +msgstr "想了解更多信息,欢迎访问:" + +#: ../../source/index.rst:29 99d292a28a794301b7cb202e0f928db7 +msgid "`Blog `__" +msgstr "`博客 `__" + +#: ../../source/index.rst:30 0ca51a3b64c94734af59c09a69f1456b +msgid "`GitHub `__" +msgstr "`GitHub `__" + +#: ../../source/index.rst:31 836732175cf0403da8537a94ad181757 +msgid "`Hugging Face `__" +msgstr "`Hugging Face `__" + +#: ../../source/index.rst:32 bea79b7409ad42bc9b555ab671bce948 +msgid "`ModelScope `__" +msgstr "`ModelScope `__" + +#: ../../source/index.rst:33 e304df6f68b44519b8ae3df43f939c5b +msgid "" +"`Qwen1.5 Collection " +"`__" +msgstr "" +"`Qwen1.5 Collection " +"`__" + +#: ../../source/index.rst:35 ec007374bc394c24a365c4459d9b0021 +msgid "" +"Join our community by joining our `Discord " +"`__ and `WeChat " +"`__ group. We" +" are looking forward to seeing you there!" +msgstr "" +"加入社区,加入 `Discord `__ 和 `微信群 " +"`__ 。很期待见到你们!" + +#: ../../source/index.rst:40 5659ef68386e4ec392fde8f9e276e5d0 +msgid "Documentation" +msgstr "文档" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/inference/chat.mo b/docs/locales/zh_CN/LC_MESSAGES/inference/chat.mo new file mode 100644 index 0000000000000000000000000000000000000000..d6ae425210e2f252f8f9395e48056ef808680966 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/inference/chat.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/inference/chat.po b/docs/locales/zh_CN/LC_MESSAGES/inference/chat.po new file mode 100644 index 0000000000000000000000000000000000000000..4e59ae174bbc9de6cc5a12cf3ad68a9c3cd73915 --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/inference/chat.po @@ -0,0 +1,85 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/inference/chat.rst:2 3d10dc3916e94e8da08d26f3cec394e8 +msgid "Using Transformers to Chat" +msgstr "使用Transformers实现Chat" + +#: ../../source/inference/chat.rst:4 ae560ca3c52141a2b7f62c37c2ef620a +msgid "" +"The most significant but also the simplest usage of Qwen1.5 is to chat " +"with it using the ``transformers`` library. In this document, we show how" +" to chat with ``Qwen1.5-7B-Chat``, in either streaming mode or not." +msgstr "Qwen1.5 最重要同时也最简单的用途是通过transformers库实现Chat功能。在本文档中,我们将展示如何在流式模式或非流式模式下与Qwen1.5-7B-Chat进行对话。" + +#: ../../source/inference/chat.rst:9 0b04962cd6f94353ad675ee83fdaa2a0 +msgid "Basic Usage" +msgstr "基本用法" + +#: ../../source/inference/chat.rst:11 cff73f0ce0bd4c53b18ff8be21a2ad4a +msgid "" +"You can just write several lines of code with ``transformers`` to chat " +"with Qwen1.5-Chat. Essentially, we build the tokenizer and the model with" +" ``from_pretrained`` method, and we use ``generate`` method to perform " +"chatting with the help of chat template provided by the tokenizer. Below " +"is an example of how to chat with Qwen1.5-7B-Chat:" +msgstr "你只需借助 ``transformers`` 库编写几行代码,就能与Qwen1.5-Chat进行对话。实质上,我们通过from_pretrained方法构建tokenizer和模型,然后利用 ``generate`` 方法,在tokenizer提供的chat template的辅助下进行chat。以下是一个如何与Qwen1.5-7B-Chat进行对话的示例:" + +#: ../../source/inference/chat.rst:56 804addcd484b4988a72f67e272294c4b +msgid "" +"Note that the previous method in the original Qwen repo ``chat()`` is now" +" replaced by ``generate()``. The ``apply_chat_template()`` function is " +"used to convert the messages into a format that the model can understand." +" The ``add_generation_prompt`` argument is used to add a generation " +"prompt, which refers to ``<|im_start|>assistant\\n`` to the input. Notably," +" we apply ChatML template for chat models following our previous " +"practice. The ``max_new_tokens`` argument is used to set the maximum " +"length of the response. The ``tokenizer.batch_decode()`` function is used" +" to decode the response. In terms of the input, the above ``messages`` is" +" an example to show how to format your dialog history and system prompt. " +"By default, if you do not specify system prompt, we directly use ``You " +"are a helpful assistant.``." +msgstr "请注意,原Qwen仓库中的旧方法 ``chat()`` 现在已被 ``generate()`` 方法替代。这里使用了 ``apply_chat_template()`` 函数将消息转换为模型能够理解的格式。其中的 ``add_generation_prompt`` 参数用于在输入中添加生成提示,该提示指向 ``<|im_start|>assistant\\n`` 。尤其需要注意的是,我们遵循先前实践,对chat模型应用ChatML模板。而 ``max_new_tokens`` 参数则用于设置响应的最大长度。此外,通过 ``tokenizer.batch_decode()`` 函数对响应进行解码。关于输入部分,上述的 ``messages`` 是一个示例,展示了如何格式化对话历史记录和系统提示。默认情况下,如果您没有指定系统提示,我们将直接使用 ``You are a helpful assistant.`` 作为系统提示。" + +#: ../../source/inference/chat.rst:70 97b15b98fc784700bad1298d1604e8dd +msgid "Streaming Mode" +msgstr "流式输出" + +#: ../../source/inference/chat.rst:72 3b1052923dd141b8b7b49451c2fa53db +msgid "" +"With the help of ``TextStreamer``, you can modify your chatting with Qwen" +" to streaming mode. Below we show you an example of how to use it:" +msgstr "借助 ``TextStreamer`` ,您可以将与Qwen的对话切换到流式传输模式。下面是一个关于如何使用它的示例:" + +#: ../../source/inference/chat.rst:89 95d10848cede405f884341ed0379849b +msgid "" +"Besides using ``TextStreamer``, we can also use ``TextIteratorStreamer`` " +"which stores print-ready text in a queue, to be used by a downstream " +"application as an iterator:" +msgstr "除了使用 ``TextStreamer`` 之外,我们还可以使用 ``TextIteratorStreamer`` ,它将可打印的文本存储在一个队列中,以便下游应用程序作为迭代器来使用:" + +#: ../../source/inference/chat.rst:111 910e04c17dd04c8e91691aff386fff2b +msgid "Next Step" +msgstr "下一步" + +#: ../../source/inference/chat.rst:113 3df342c8e1af454994600742e06e7bc9 +msgid "" +"Now you can chat with Qwen1.5 in either streaming mode or not. Continue " +"to read the documentation and try to figure out more advanced usages of " +"model inference!" +msgstr "现在,你可以选择流式模式或非流式模式与Qwen1.5进行对话。继续阅读文档,并尝试探索模型推理的更多高级用法!"" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/quantization/awq.mo b/docs/locales/zh_CN/LC_MESSAGES/quantization/awq.mo new file mode 100644 index 0000000000000000000000000000000000000000..ca5a00507030437289ff5f4c6e4c8358386e8c77 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/quantization/awq.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/quantization/awq.po b/docs/locales/zh_CN/LC_MESSAGES/quantization/awq.po new file mode 100644 index 0000000000000000000000000000000000000000..2697108c459e290e586eb8cb0755cac077e332a6 --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/quantization/awq.po @@ -0,0 +1,109 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/quantization/awq.rst:2 bab75f352096428a9dee89930ab02e7a +msgid "AWQ" +msgstr "AWQ" + +#: ../../source/quantization/awq.rst:4 517d6f4ca69247f7b08087dd995cf1a6 +msgid "" +"For quantized models, one of our recommendations is the usage of `AWQ " +"`__ with `AutoAWQ `__. AWQ refers to Activation-aware Weight " +"Quantization, a hardware-friendly approach for LLM low-bit weight-only " +"quantization. AutoAWQ is an easy-to-use package for 4-bit quantized " +"models. AutoAWQ speeds up models by 3x and reduces memory requirements by" +" 3x compared to FP16. AutoAWQ implements the Activation-aware Weight " +"Quantization (AWQ) algorithm for quantizing LLMs. In this document, we " +"show you how to use the quantized model with Transformers and also how to" +" quantize your own model." +msgstr "对于量化模型,我们推荐使用 `AWQ `__ 结合 `AutoAWQ `__ 。AWQ即激活感知权重量化,是一种针对LLM的低比特权重量化的硬件友好方法。而AutoAWQ是一个易于使用的工具包,专门用于4比特量化模型。相较于FP16,AutoAWQ能够将模型的运行速度提升3倍,并将内存需求降低至原来的1/3。AutoAWQ实现了激活感知权重量化(AWQ)算法,可用于LLM的量化处理。在本文档中,我们将向您展示如何在Transformers框架下使用量化模型,以及如何对您自己的模型进行量化。" + +#: ../../source/quantization/awq.rst:16 4f843dc502354b71ba29fdc918bdff73 +msgid "Usage of AWQ Quantized Models with Transformers" +msgstr "如何在Transformers中使用AWQ量化模型" + +#: ../../source/quantization/awq.rst:18 0984fc07bb83453ba4dcfe68e7e4ff76 +msgid "" +"Now, Transformers has officially supported AutoAWQ, which means that you " +"can directly use the quantized model with Transformers. The following is " +"a very simple code snippet showing how to run ``Qwen1.5-7B-Chat-AWQ`` " +"with the quantized model:" +msgstr "现在,Transformers已经正式支持AutoAWQ,这意味着您可以直接在Transformers中使用量化模型。以下是一个非常简单的代码片段,展示如何运行量化模型 ``Qwen1.5-7B-Chat-AWQ`` :" + +#: ../../source/quantization/awq.rst:57 e0eb738bce98432ea115745392b5e826 +msgid "Usage of AWQ Quantized Models with vLLM" +msgstr "如何在vLLM中使用AWQ量化模型" + +#: ../../source/quantization/awq.rst:59 9e96a6878cda41ef935fe77629492c60 +msgid "" +"vLLM has supported AWQ, which means that you can directly use our " +"provided AWQ models or those trained with ``AutoAWQ`` with vLLM. " +"Actually, the usage is the same with the basic usage of vLLM. We provide " +"a simple example of how to launch OpenAI-API compatible API with vLLM and" +" ``Qwen1.5-7B-Chat-AWQ``:" +msgstr "vLLM 已经支持了AWQ,这意味着您可以直接使用我们提供的AWQ模型,或者是通过AutoAWQ训练得到的与vLLM兼容的模型。实际上,其用法与vLLM的基本用法相同。我们提供了一个简单的示例,展示了如何通过vLLM启动与OpenAI API兼容的接口,并使用 ``Qwen1.5-7B-Chat-AWQ`` 模型:" + +#: ../../source/quantization/awq.rst:79 4143e0d33e5044ee9cb5f712c6fa0b3a +msgid "" +"or you can use python client with ``openai`` python package as shown " +"below:" +msgstr "或者你可以按照下面所示的方式,使用 ``openai`` Python包中的Python客户端:" + +#: ../../source/quantization/awq.rst:104 6a6eb6b49b864b9483b8b7e75a644eaa +msgid "Quantize Your Own Model with AutoAWQ" +msgstr "使用AutoAWQ量化你的模型" + +#: ../../source/quantization/awq.rst:106 883826b500fe44c2bf8cfe1c6e817f85 +msgid "" +"If you want to quantize your own model to AWQ quantized models, we advise" +" you to use AutoAWQ. It is suggested installing the latest version of the" +" package by installing from source code:" +msgstr "如果您希望将自定义模型量化为AWQ量化模型,我们建议您使用AutoAWQ。推荐通过安装源代码来获取并安装该工具包的最新版本:" + +#: ../../source/quantization/awq.rst:116 b70a51920b4444abac3843c56f0b1a6a +msgid "" +"Suppose you have finetuned a model based on ``Qwen1.5-7B``, which is " +"named ``Qwen1.5-7B-finetuned``, with your own dataset, e.g., Alpaca. To " +"build your own AWQ quantized model, you need to use the training data for" +" calibration. Below, we provide a simple demonstration for you to run:" +msgstr "假设你已经基于 ``Qwen1.5-7B`` 模型进行了微调,并将其命名为 ``Qwen1.5-7B-finetuned`` ,且使用的是你自己的数据集,比如Alpaca。若要构建你自己的AWQ量化模型,你需要使用训练数据进行校准。以下,我们将为你提供一个简单的演示示例以便运行:" + +#: ../../source/quantization/awq.rst:136 d9f8d6987a2e436d8a50d57ff36cfa30 +msgid "" +"Then you need to prepare your data for calibaration. What you need to do " +"is just put samples into a list, each of which is a text. As we directly " +"use our finetuning data for calibration, we first format it with ChatML " +"template. For example:" +msgstr "接下来,您需要准备数据以进行校准。您需要做的就是将样本放入一个列表中,其中每个样本都是一段文本。由于我们直接使用微调数据来进行校准,所以我们首先使用ChatML模板对其进行格式化。例如:" + +#: ../../source/quantization/awq.rst:149 635319f729684f319b0ec092ad8e40d6 +msgid "where each ``msg`` is a typical chat message as shown below:" +msgstr "其中每个 ``msg`` 是一个典型的聊天消息,如下所示:" + +#: ../../source/quantization/awq.rst:159 b324715402c94122a01cacbb1b312d88 +msgid "Then just run the calibration process by one line of code:" +msgstr "然后只需通过一行代码运行校准过程:" + +#: ../../source/quantization/awq.rst:165 e5d0fe0d78fa4ee3933913c9d8fb004c +msgid "Finally, save the quantized model:" +msgstr "最后,保存量化模型:" + +#: ../../source/quantization/awq.rst:172 4de18a17e5c548bcb9aa6b464ce5a473 +msgid "Then you can obtain your own AWQ quantized model for deployment. Enjoy!" +msgstr "然后你就可以得到一个可以用于部署的AWQ量化模型。玩得开心!" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/quantization/gguf.mo b/docs/locales/zh_CN/LC_MESSAGES/quantization/gguf.mo new file mode 100644 index 0000000000000000000000000000000000000000..91e862e920b57dc83f64b492e9ea8283f43818d3 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/quantization/gguf.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/quantization/gguf.po b/docs/locales/zh_CN/LC_MESSAGES/quantization/gguf.po new file mode 100644 index 0000000000000000000000000000000000000000..6c1d51a78e86a61b4ce6ecbc3e061c39e00b0cdf --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/quantization/gguf.po @@ -0,0 +1,108 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/quantization/gguf.rst:2 79e40c40b83d4f6d9bb98c1dd1b1ef71 +msgid "GGUF" +msgstr "GGUF" + +#: ../../source/quantization/gguf.rst:4 14be5842d732404796a6f550f14a7bdd +msgid "" +"Recently, running LLMs locally is popular in the community, and running " +"GGUF files with llama.cpp is a typical example. With llama.cpp, you can " +"not only build GGUF files for your models but also perform low-bit " +"quantization. In GGUF, you can directly quantize your models without " +"calibration, or apply the AWQ scale for better quality, or use imatrix " +"with calibration data. In this document, we demonstrate the simplest way " +"to quantize your model as well as the way to apply AWQ scale to your Qwen" +" model quantization." +msgstr "最近,在社区中本地运行LLM变得越来越流行,其中使用llama.cpp处理GGUF文件是一个典型的例子。通过llama.cpp,您不仅可以为自己的模型构建GGUF文件,还可以进行低比特量化操作。在GGUF格式下,您可以直接对模型进行量化而无需校准过程,或者为了获得更好的量化效果应用AWQ scale,亦或是结合校准数据使用imatrix工具。在这篇文档中,我们将展示最简便的模型量化方法,以及如何在对Qwen模型进行量化时应用AWQ比例以优化其质量。" + +#: ../../source/quantization/gguf.rst:14 80a49bd4e8be44c0a76fba918f1ec373 +msgid "Quantize Your Models and Make GGUF Files" +msgstr "量化你的模型并生成GGUF文件" + +#: ../../source/quantization/gguf.rst:16 dccc5a60aeea4bb49045d4b5f37fc8ec +msgid "" +"Before you move to quantization, make sure you have followed the " +"instruction and started to use llama.cpp. The following guidance will NOT" +" provide instructions about installation and building. Now, suppose you " +"would like to quantize ``Qwen1.5-7B-Chat``. You need to first make a GGUF" +" file for the fp16 model as shown below:" +msgstr "在进行量化操作之前,请确保你已经按照指导开始使用llama.cpp。以下指引将不会提供有关安装和构建的步骤。现在,假设你要对 ``Qwen1.5-7B-Chat`` 模型进行量化,首先需要按照如下所示的方式为fp16模型创建一个GGUF文件:" + +#: ../../source/quantization/gguf.rst:26 0f97df4b989e4cea92ec0fe41f8dbd0b +msgid "" +"where the first argument refers to the path to the HF model directory or " +"the HF model name, and the second argument refers to the path of your " +"output GGUF file (here I just put it under the directory ``models/7B``. " +"Remember to create the directory before you run the command). In this " +"way, you have generated a GGUF file for your fp16 model, and you then " +"need to quantize it to low bits based on your requirements. An example of" +" quantizing the model to 4 bits is shown below:" +msgstr ""其中,第一个参数指代的是预训练模型所在的路径或者HF模型的名称,第二个参数则指的是你想要生成的GGUF文件的路径(此处我将其置于 ``models/7B`` 目录下)。请记住,在运行命令之前,需要先创建这个目录。通过这种方式,你已经为你的fp16模型生成了一个GGUF文件,接下来你需要根据实际需求将其量化至低比特位。以下是一个将模型量化至4位的具体示例:"" + +#: ../../source/quantization/gguf.rst:38 65e715f3392c4fd58ce4884f54da40c5 +msgid "" +"where we use ``q4_0`` for the 4-bit quantization. Until now, you have " +"finished quantizing a model to 4 bits and putting it into a GGUF file, " +"which can be run directly with llama.cpp." +msgstr "到现在为止,您已经完成了将模型量化为4比特,并将其放入GGUF文件中。这里的 ``q4_0`` 表示4比特量化。现在,这个量化后的模型可以直接通过llama.cpp运行。" + +#: ../../source/quantization/gguf.rst:43 4dcc797b636f486da31d32535fdc9f6d +msgid "Quantize Your Models With AWQ Scales" +msgstr "利用AWQ scales来量化你的模型" + +#: ../../source/quantization/gguf.rst:45 8b17749b06b54091bf660ffb88974e8e +msgid "" +"To improve the quality of your quantized models, one possible solution is" +" to apply the AWQ scale, following `this script `__. First of all, when" +" you run ``model.quantize()`` with AutoAWQ, remember to add " +"``export_compatible=True`` as shown below:" +msgstr "要提升量化模型的质量,一种可能的解决方案是应用AWQ scales。具体操作步骤如下:首先,在使用AutoAWQ运行model.quantize()时,请务必记得添加 ``export_compatible=True`` 参数,如下所示:" + +#: ../../source/quantization/gguf.rst:62 9bc945e98396439c9c2eeafef825d2fd +msgid "" +"With ``model.save_quantzed()`` as shown above, a fp16 model with AWQ " +"scales is saved. Then, when you run ``convert-hf-to-gguf.py``, remember " +"to replace the model path with the path to the fp16 model with AWQ " +"scales, e.g.," +msgstr "通过上述的 model.save_quantized(),一个带有AWQ scales的fp16模型将被保存。然后,当你运行 ``convert-hf-to-gguf.py`` 脚本时,请记得将模型路径替换为带有AWQ scales的fp16模型的路径,例如:" + +#: ../../source/quantization/gguf.rst:71 384fbacfe6984c95b3cbcd68cd3dcd5d +msgid "" +"In this way, you can apply the AWQ scales to your quantized models in " +"GGUF formats, which helps improving the model quality." +msgstr "通过这种方式,您可以在GGUF格式的量化模型中应用AWQ scales,这有助于提升模型的质量。" + +#: ../../source/quantization/gguf.rst:74 b492d0f21b6b44d2b17cafaef752177f +msgid "" +"We usually quantize the fp16 model to 2, 3, 4, 5, 6, and 8-bit models. To" +" perform different low-bit quantization, just replace the quantization " +"method in your command. For example, if you want to quantize your model " +"to 2-bit model, you can replace ``q4_0`` to ``q2_k`` as demonstrated " +"below:" +msgstr "我们通常将fp16模型量化为2、3、4、5、6和8位模型。要执行不同低比特的量化,只需在命令中替换量化方法即可。例如,如果你想将你的模型量化为2位模型,你可以按照下面所示,将 ``q4_0`` 替换为 ``q2_k`` :" + +#: ../../source/quantization/gguf.rst:84 9b51095b2c6f4b258bf5aec039471953 +msgid "" +"We now provide GGUF models in the following quantization levels: " +"``q2_k``, ``q3_k_m``, ``q4_0``, ``q4_k_m``, ``q5_0``, ``q5_k_m``, " +"``q6_k``, and ``q8_0``. For more information, please visit `llama.cpp " +"`__." +msgstr "我们现在提供了以下量化级别的GGUF模型: ``q2_k`` 、 ``q3_k_m`` 、 ``q4_0`` 、 ``q4_k_m`` 、 ``q5_0`` 、 ``q5_k_m`` 、 ``q6_k`` 和 ``q8_0`` 。 欲了解更多信息,请访问 `llama.cpp `__ 。" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/quantization/gptq.mo b/docs/locales/zh_CN/LC_MESSAGES/quantization/gptq.mo new file mode 100644 index 0000000000000000000000000000000000000000..f762b7287eb96ac1df69ad9616e56ffc09465739 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/quantization/gptq.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/quantization/gptq.po b/docs/locales/zh_CN/LC_MESSAGES/quantization/gptq.po new file mode 100644 index 0000000000000000000000000000000000000000..b9a2a4afd158952b0f00dfe6faec821b518eb511 --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/quantization/gptq.po @@ -0,0 +1,109 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/quantization/gptq.rst:2 41077c7d75ad44bba5cff56fef7a54bd +msgid "GPTQ" +msgstr "GPTQ" + +#: ../../source/quantization/gptq.rst:4 c291d8c4012b4ac58b42b37c04ac3f05 +msgid "" +"`GPTQ `__ is a quantization method for " +"GPT-like LLMs, which uses one-shot weight quantization based on " +"approximate second-order information. In this document, we show you how " +"to use the quantized model with transformers and also how to quantize " +"your own model with `AutoGPTQ `__." +msgstr "`GPTQ `__ 是一种针对类GPT大型语言模型的量化方法,它基于近似二阶信息进行一次性权重量化。在本文档中,我们将向您展示如何使用 ``transformers`` 库加载并应用量化后的模型,同时也会指导您如何通过 `AutoGPTQ `__ 来对您自己的模型进行量化处理。" + +#: ../../source/quantization/gptq.rst:11 ba8f325751ea460b8d3b9d8665f82e7c +msgid "Usage of GPTQ Models with Transformers" +msgstr "在Transformers中使用GPTQ模型" + +#: ../../source/quantization/gptq.rst:13 290140b39fd24e9698933f1a4b3e140f +msgid "" +"Now, Transformers has officially supported AutoGPTQ, which means that you" +" can directly use the quantized model with Transformers. The following is" +" a very simple code snippet showing how to run ``Qwen1.5-7B-Chat-GPTQ-" +"Int8`` (note that for each size of Qwen1.5, we provide both Int4 and Int8" +" quantized models) with the quantized model:" +msgstr "现在,Transformers 正式支持了AutoGPTQ,这意味着您能够直接在Transformers中使用量化后的模型。以下是一个非常简单的代码片段示例,展示如何运行 ``Qwen1.5-7B-Chat-GPTQ-Int8`` (请注意,对于每种大小的Qwen1.5模型,我们都提供了Int4和Int8两种量化版本):" + +#: ../../source/quantization/gptq.rst:53 fea96fa1c4344b37a5492a2136f38667 +msgid "Usage of GPTQ Quantized Models with vLLM" +msgstr "在vLLM中使用GPTQ量化模型" + +#: ../../source/quantization/gptq.rst:55 0f8eee84b4664c6db0e2383b44f92ca1 +msgid "" +"vLLM has supported GPTQ, which means that you can directly use our " +"provided GPTQ models or those trained with ``AutoGPTQ`` with vLLM. " +"Actually, the usage is the same with the basic usage of vLLM. We provide " +"a simple example of how to launch OpenAI-API compatible API with vLLM and" +" ``Qwen1.5-7B-Chat-GPTQ-Int8``:" +msgstr "vLLM 已经支持了GPTQ,这意味着您可以直接使用我们提供的GPTQ模型,或者那些通过AutoGPTQ训练得到的模型与vLLM结合使用。实际上,其用法与vLLM的基本用法相同。我们提供了一个简单的示例,展示了如何使用vLLM以及 ``Qwen1.5-7B-Chat-GPTQ-Int8`` 模型启动与OpenAI API兼容的API:" + +#: ../../source/quantization/gptq.rst:75 66259f71f06f437d83e467853aad4e91 +msgid "" +"or you can use python client with ``openai`` python package as shown " +"below:" +msgstr "或者你可以按照下面所示的方式,使用 ``openai`` Python包中的Python客户端:" + +#: ../../source/quantization/gptq.rst:100 ebb1ebce02da4f78aa2d9dbce73a92d5 +msgid "Quantize Your Own Model with AutoGPTQ" +msgstr "使用AutoGPTQ量化你的模型" + +#: ../../source/quantization/gptq.rst:102 e0e9185eec504db59ae92b48cbb5f039 +msgid "" +"If you want to quantize your own model to GPTQ quantized models, we " +"advise you to use AutoGPTQ. It is suggested installing the latest version" +" of the package by installing from source code:" +msgstr "如果你想将自定义模型量化为GPTQ量化模型,我们建议你使用AutoGPTQ工具。推荐通过安装源代码的方式获取并安装最新版本的该软件包。" + +#: ../../source/quantization/gptq.rst:112 2f85adf755994b5c8566acdcd9b40bdb +msgid "" +"Suppose you have finetuned a model based on ``Qwen1.5-7B``, which is " +"named ``Qwen1.5-7B-finetuned``, with your own dataset, e.g., Alpaca. To " +"build your own GPTQ quantized model, you need to use the training data " +"for calibration. Below, we provide a simple demonstration for you to run:" +msgstr "假设你已经基于 ``Qwen1.5-7B`` 模型进行了微调,并将该微调后的模型命名为 ``Qwen1.5-7B-finetuned`` ,且使用的是自己的数据集,比如Alpaca。要构建你自己的GPTQ量化模型,你需要使用训练数据进行校准。以下是一个简单的演示示例,供你参考运行:" + +#: ../../source/quantization/gptq.rst:143 1a0c345f405c44c7b59710cafa099951 +msgid "" +"Then you need to prepare your data for calibaration. What you need to do " +"is just put samples into a list, each of which is a text. As we directly " +"use our finetuning data for calibration, we first format it with ChatML " +"template. For example:" +msgstr "接下来,你需要准备数据进行校准。你需要做的是将样本放入一个列表中,其中每个样本都是一段文本。由于我们直接使用微调数据进行校准,所以我们首先使用ChatML模板对它进行格式化处理。例如:" + +#: ../../source/quantization/gptq.rst:158 58188538413049bcbe47270f9eb40d68 +msgid "where each ``msg`` is a typical chat message as shown below:" +msgstr "接下来,你需要准备数据以进行校准。你需要做的就是将样本放入一个列表中,其中每个样本都是文本。由于我们直接使用微调数据来进行校准,所以我们首先使用ChatML模板来格式化它。例如:" + +#: ../../source/quantization/gptq.rst:168 e42b03c4aeeb41caac04a7fbfd2e5925 +msgid "Then just run the calibration process by one line of code:" +msgstr "然后只需通过一行代码运行校准过程:" + +#: ../../source/quantization/gptq.rst:177 edcb18775f864566b47befa8e03b6277 +msgid "Finally, save the quantized model:" +msgstr "最后,保存量化模型:" + +#: ../../source/quantization/gptq.rst:184 ea6f6d3200904260b4e67cf5e7b29467 +msgid "" +"It is unfortunate that the ``save_quantized`` method does not support " +"sharding. For sharding, you need to load the model and use " +"``save_pretrained`` from transformers to save and shard the model. Except" +" for this, everything is so simple. Enjoy!" +msgstr "很遗憾, ``save_quantized`` 方法不支持模型分片。若要实现模型分片,您需要先加载模型,然后使用来自 ``transformers`` 库的 ``save_pretrained`` 方法来保存并分片模型。除此之外,一切操作都非常简单。祝您使用愉快!" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/run_locally/llama.cpp.mo b/docs/locales/zh_CN/LC_MESSAGES/run_locally/llama.cpp.mo new file mode 100644 index 0000000000000000000000000000000000000000..f0f667aa5c95f5eadf3819062719e8a3d6781235 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/run_locally/llama.cpp.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/run_locally/llama.cpp.po b/docs/locales/zh_CN/LC_MESSAGES/run_locally/llama.cpp.po new file mode 100644 index 0000000000000000000000000000000000000000..ef4d0c0115b68f3968979327d6f73bf613db009c --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/run_locally/llama.cpp.po @@ -0,0 +1,144 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-03-04 15:21+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/run_locally/llama.cpp.rst:2 9295ae9f5a5f45bfab93b7e8518e8f08 +msgid "llama.cpp" +msgstr "llama.cpp" + +#: ../../source/run_locally/llama.cpp.rst:4 b13bc91c8a9a4571839cb73e37761d1d +msgid "" +"`llama.cpp `__ is a C++ library " +"for LLM inference with mimimal setup. It enables running Qwen on your " +"local machine. It is a plain C/C++ implementation without dependencies, " +"and it has AVX, AVX2 and AVX512 support for x86 architectures. It " +"provides 2, 3, 4, 5, 6, and 8-bit quantization for faster inference and " +"reduced memory footprint. CPU+GPU hybrid inference to partially " +"accelerate models larger than the total VRAM capacity is also supported. " +"Essentially, the usage of llama.cpp is to run the GGUF (GPT-Generated " +"Unified Format ) models. For more information, please refer to the " +"official GitHub repo. Here we demonstrate how to run Qwen with llama.cpp." +msgstr "" +"`llama.cpp `__ " +"是一个C++库,用于简化LLM推理的设置。它使得在本地机器上运行Qwen成为可能。该库是一个纯C/C++实现,不依赖任何外部库,并且针对x86架构提供了AVX、AVX2和AVX512加速支持。此外,它还提供了2、3、4、5、6以及8位量化功能,以加快推理速度并减少内存占用。对于大于总VRAM容量的大规模模型,该库还支持CPU+GPU混合推理模式进行部分加速。本质上,llama.cpp的用途在于运行GGUF(由GPT生成的统一格式)模型。欲了解更多详情,请参阅官方GitHub仓库。以下我们将演示如何使用llama.cpp运行Qwen。" + +#: ../../source/run_locally/llama.cpp.rst:17 7296806f5b8f469387080e1658c355ed +msgid "Prerequisites" +msgstr "准备" + +#: ../../source/run_locally/llama.cpp.rst:19 33c80a9748744bfe8580b781834fe204 +msgid "" +"This example is for the usage on Linux or MacOS. For the first step, " +"clone the repo and enter the directory:" +msgstr "这个示例适用于Linux或MacOS系统。第一步操作是: “克隆仓库并进入该目录:" + +#: ../../source/run_locally/llama.cpp.rst:27 023579e4d3e948fbaf2a2e358cc71d59 +msgid "Then use ``make``:" +msgstr "然后运行 ``make`` 命令:" + +#: ../../source/run_locally/llama.cpp.rst:33 513bfba9842b483687c4e1b4e5b2a092 +msgid "Then you can run GGUF files with ``llama.cpp``." +msgstr "然后你就能使用 ``llama.cpp`` 运行GGUF文件。" + +#: ../../source/run_locally/llama.cpp.rst:36 ffbbe87d16bc4205aa246fcf1216a9b7 +msgid "Running Qwen GGUF Files" +msgstr "运行Qwen的GGUF文件" + +#: ../../source/run_locally/llama.cpp.rst:38 06afbf066c6442c68f45d1a90bd68b7c +msgid "" +"We provide a series of GGUF models in our Hugging Face organization, and " +"to search for what you need you can search the repo names with ``-GGUF``." +" Download the GGUF model that you want with ``huggingface-cli`` (you need" +" to install it first with ``pip install huggingface_hub``):" +msgstr "" +"我们在Hugging Face组织中提供了一系列GGUF模型,为了找到您需要的模型,您可以搜索仓库名称中包含 ``-GGUF`` " +"的部分。要下载所需的GGUF模型,请使用 ``huggingface-cli`` (首先需要通过命令 ``pip install " +"huggingface_hub`` 安装它):" + +#: ../../source/run_locally/llama.cpp.rst:48 4f94dc408d9641e686d64d0508cb7d3f +msgid "for example:" +msgstr "比如:" + +#: ../../source/run_locally/llama.cpp.rst:54 3333b60028d74c5ea09d3fa42c22af4c +msgid "Then you can run the model with the following command:" +msgstr "然后你可以用如下命令运行模型:" + +#: ../../source/run_locally/llama.cpp.rst:60 1dd4d5e214df4b4a8c4b4236d2b40caa +msgid "" +"where ``-n`` refers to the maximum number of tokens to generate. There " +"are other hyperparameters for you to choose and you can run" +msgstr "``-n`` 指的是要生成的最大token数量。这里还有其他超参数供你选择,并且你可以运行" + +#: ../../source/run_locally/llama.cpp.rst:67 1418c6357ce942a7880167048985755d +msgid "to figure them out." +msgstr "以了解它们。" + +#: ../../source/run_locally/llama.cpp.rst:70 688ee9f001ec4085b4d93caea7aeb036 +msgid "Make Your GGUF Files" +msgstr "生成你的GGUF文件" + +#: ../../source/run_locally/llama.cpp.rst:72 404521aabf484cb2aa304a78f23a63db +#, fuzzy +msgid "" +"We introduce the method of creating and quantizing GGUF files in " +"`quantization/llama.cpp <../quantization/gguf.html>`__. You can refer to " +"that document for more information." +msgstr "" +"我们在 `quantization/llama.cpp <../quantization/gguf.html>`__ " +"中介绍了创建和量化GGUF文件的方法。您可以参考该文档获取更多信息。" + +#: ../../source/run_locally/llama.cpp.rst:77 524dc22e5deb490b9191b674281d2bd9 +msgid "Perplexity Evaluation" +msgstr "PPL评测" + +#: ../../source/run_locally/llama.cpp.rst:79 c2df95294edf4f0b8de7f92c4e63b604 +msgid "" +"``llama.cpp`` provides methods for us to evaluate the perplexity " +"performance of the GGUF models. To do this, you need to prepare the " +"dataset, say \"wiki test\". Here we demonstrate an example to run the " +"test." +msgstr "llama.cpp为我们提供了评估GGUF模型PPL性能的方法。为了实现这一点,你需要准备一个数据集,比如“wiki测试”。这里我们展示了一个运行测试的例子。" + +#: ../../source/run_locally/llama.cpp.rst:84 2b96c26557914be28d5d246775b657cd +msgid "For the first step, download the dataset:" +msgstr "第一步,下载数据集:" + +#: ../../source/run_locally/llama.cpp.rst:91 fb0bc11477524f07b6e195757f152d92 +msgid "Then you can run the test with the following command:" +msgstr "然后你可以用如下命令运行测试:" + +#: ../../source/run_locally/llama.cpp.rst:97 6822a2aaaa5141ea9be44c569b4a440f +msgid "where the output is like" +msgstr "输出如下所示" + +#: ../../source/run_locally/llama.cpp.rst:105 cca21a6ce70d445fbb23ca92cafc574d +msgid "Wait for some time and you will get the perplexity of the model." +msgstr "稍等一段时间你将得到模型的PPL评测结果。" + +#: ../../source/run_locally/llama.cpp.rst:108 f3df6de18c0d4b78ad29738580cab53a +msgid "Use GGUF with LM Studio" +msgstr "在LM Studio使用GGUF" + +#: ../../source/run_locally/llama.cpp.rst:110 e901df85221a4887b98a3a5c540f010a +msgid "" +"If you still find it difficult to use ``llama.cpp``, I advise you to play" +" with `LM Studio `__, which is a platform for your " +"to search and run local LLMs. Qwen1.5 has already been officially part of" +" LM Studio. Have fun!" +msgstr "" +"如果你仍然觉得使用llama.cpp有困难,我建议你尝试一下 `LM Studio `__ " +"这个平台,它允许你搜索和运行本地的大规模语言模型。Qwen1.5已经正式成为LM Studio的一部分。祝你使用愉快!" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/run_locally/ollama.mo b/docs/locales/zh_CN/LC_MESSAGES/run_locally/ollama.mo new file mode 100644 index 0000000000000000000000000000000000000000..b894a125206ed7b2f0130911dc2f263753608319 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/run_locally/ollama.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/run_locally/ollama.po b/docs/locales/zh_CN/LC_MESSAGES/run_locally/ollama.po new file mode 100644 index 0000000000000000000000000000000000000000..57f055bc0a5c1932f021a56d51cbf7a8ca3ad560 --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/run_locally/ollama.po @@ -0,0 +1,89 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/run_locally/ollama.rst:2 5dbfc8ae09a24c89964f37ebd4ca66bd +msgid "Ollama" +msgstr "Ollama" + +#: ../../source/run_locally/ollama.rst:4 ba8364b5fce64dedabeb7cfbcf677675 +msgid "" +"`Ollama `__ helps you run LLMs locally with only a " +"few commands. It is available at MacOS, Linux, and Windows. Now, Qwen1.5 " +"is officially on Ollama, and you can run it with one command:" +msgstr "`Ollama `__ 帮助您通过少量命令即可在本地运行LLM。它适用于MacOS、Linux和Windows操作系统。现在,Qwen1.5正式上线Ollama,您只需一条命令即可运行它:" + +#: ../../source/run_locally/ollama.rst:12 93533ba6809b42c19a936440d86df528 +msgid "Next, we introduce more detailed usages of Ollama for running Qwen models." +msgstr "接着,我们介绍在Ollama使用Qwen模型的更多用法" + +#: ../../source/run_locally/ollama.rst:16 a972d55b2d0e4ec1b9046258d7342d09 +msgid "Quickstart" +msgstr "快速开始" + +#: ../../source/run_locally/ollama.rst:18 494ac69706fb4581b63e8eb81b91148b +msgid "" +"Visit the official website `Ollama `__ and click " +"download to install Ollama on your device. You can also search models in " +"the website, where you can find the Qwen1.5 models. Except for the " +"default one, you can choose to run Qwen1.5-Chat models of different sizes" +" by:" +msgstr "访问官方网站 `Ollama `__ ”,点击 ``Download`` 以在您的设备上安装Ollama。您还可以在网站上搜索模型,在这里您可以找到Qwen1.5系列模型。除了默认模型之外,您可以通过以下方式选择运行不同大小的Qwen1.5-Chat模型:" + +#: ../../source/run_locally/ollama.rst:24 2aa16e7c8f2144958e5682603c54729c +msgid "``ollama run qwen:0.5b``" +msgstr "" + +#: ../../source/run_locally/ollama.rst:25 e409605f90f64c9383f2fd7401b51b69 +msgid "``ollama run qwen:1.8b``" +msgstr "" + +#: ../../source/run_locally/ollama.rst:26 eb4a5cd83bd944acb4576566d6ef39ab +msgid "``ollama run qwen:4b``" +msgstr "" + +#: ../../source/run_locally/ollama.rst:27 53dd5fcbf9794c6fa9351ac89c59896f +msgid "``ollama run qwen:7b``" +msgstr "" + +#: ../../source/run_locally/ollama.rst:28 56ed4eb4153643ccae8a59abd9b8cf99 +msgid "``ollama run qwen:14b``" +msgstr "" + +#: ../../source/run_locally/ollama.rst:29 b3e49968c75545f7b291dd7ae099fb8b +msgid "``ollama run qwen:72b``" +msgstr "" + +#: ../../source/run_locally/ollama.rst:32 52d43c07a68b428692fbb19ccb6e1813 +msgid "Run Ollama with Your GGUF Files" +msgstr "在Ollama运行你的GGUF文件" + +#: ../../source/run_locally/ollama.rst:34 948e45e8c2aa4cadb9246d2a4d94c3f3 +msgid "" +"Sometimes you don't want to pull models and you just want to use Ollama " +"with your own GGUF files. Suppose you have a GGUF file of Qwen, ``qwen1_5" +"-7b-chat-q4_0.gguf``. For the first step, you need to create a file " +"called ``Modelfile``. The content of the file is shown below:" +msgstr "有时您可能不想拉取模型,而是希望直接使用自己的GGUF文件来配合Ollama。假设您有一个名为 ``qwen1_5-7b-chat-q4_0.gguf`` 的Qwen的GGUF文件。在第一步中,您需要创建一个名为 ``Modelfile`` 的文件。该文件的内容如下所示:" + +#: ../../source/run_locally/ollama.rst:61 3843d0ede09345ce8f694bc19399b780 +msgid "Then create the ollama model by running:" +msgstr "然后通过运行下列命令来创建一个ollama模型" + +#: ../../source/run_locally/ollama.rst:67 c061968787654e92ae68ef9a8d2a19ed +msgid "Once it is finished, you can run your ollama model by:" +msgstr "完成后,你即可运行你的ollama模型:" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/training/SFT/example.mo b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/example.mo new file mode 100644 index 0000000000000000000000000000000000000000..a5193281935286033db4937c907db1f4b0f29f77 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/example.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/training/SFT/example.po b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/example.po new file mode 100644 index 0000000000000000000000000000000000000000..93384340666b38ec7a8af083237d4c1229a3862a --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/example.po @@ -0,0 +1,305 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/training/SFT/example.rst:2 691e3f2b49604b49a99b0d62c21ab625 +msgid "Example" +msgstr "示例" + +#: ../../source/training/SFT/example.rst:4 ad35293ab62442db89b6b6d2334b0415 +msgid "" +"Here we provide a very simple script for supervised finetuning, which is " +"revised from the training script in ```Fastchat`` `__. The script is used to finetune Qwen with Hugging Face " +"Trainer. You can check the script `here " +"`__. This script" +" for supervised finetuning (SFT) has the following features:" +msgstr "在这里,我们提供了一个非常简单的有监督微调脚本,该脚本是基于 `Fastchat `__ 的训练脚本修改而来的。这个脚本用于使用Hugging Face Trainer 对Qwen模型进行微调。你可以在以下链接查看这个脚本: `这里 `__ 。这个脚本具有以下特点:" + +#: ../../source/training/SFT/example.rst:11 d058261c295d4c62ab51212928663d67 +msgid "Support single-GPU and multi-GPU training;" +msgstr "支持单卡和多卡分布式训练" + +#: ../../source/training/SFT/example.rst:12 73732e5202a048ad9bd628046779d3a2 +msgid "" +"Support full-parameter tuning, `LoRA " +"`__, and `Q-LoRA " +"`__." +msgstr "支持全参数微调、 `LoRA `__ 以及 `Q-LoRA `__ 。" + +#: ../../source/training/SFT/example.rst:16 4691f21f4b19470ba7c587c0a2c21f49 +msgid "In the following, we introduce more details about the usage of the script." +msgstr "下面,我们介绍脚本的更多细节。" + +#: ../../source/training/SFT/example.rst:20 fe662acf1951448c959543a3c74c8417 +msgid "Installation" +msgstr "安装" + +#: ../../source/training/SFT/example.rst:22 e412d1f6dda44df3b6792975b6124c10 +msgid "Before you start, make sure you have installed the following packages:" +msgstr "开始之前,确保你已经安装了以下代码库:" + +#: ../../source/training/SFT/example.rst:29 4cf9efbe517045778d847fd3adef663a +msgid "Data Preparation" +msgstr "准备数据" + +#: ../../source/training/SFT/example.rst:31 07e875e969504388b10b7ada5b4c3c7d +msgid "" +"For data preparation, we advise you to organize the data in a jsonl file," +" where each line is a dictionary as demonstrated below:" +msgstr "我们建议你放在jsonl文件中,每一行是一个如下所示的字典:" + +#: ../../source/training/SFT/example.rst:76 652ddb9b02594421bde769f553d29a3e +msgid "" +"Above are two examples of each data sample in the dataset. Each sample is" +" a JSON object with the following fields: ``type``, ``messages`` and " +"``source``. ``messages`` is required while the others are optional for " +"you to label your data format and data source. The ``messages`` field is " +"a list of JSON objects, each of which has two fields: ``role`` and " +"``content``. ``role`` can be ``system``, ``user``, or ``assistant``. " +"``content`` is the text of the message. ``source`` is the source of the " +"data, which can be ``self-made``, ``alpaca``, ``open-hermes``, or any " +"other string." +msgstr "以上提供了该数据集中的每个样本的两个示例。每个样本都是一个JSON对象,包含以下字段: ``type`` 、 ``messages`` 和 ``source`` 。其中, ``messages`` 是必填字段,而其他字段则是供您标记数据格式和数据来源的可选字段。 ``messages`` 字段是一个JSON对象列表,每个对象都包含两个字段: ``role`` 和 ``content`` 。其中, ``role`` 可以是 ``system`` 、 ``user`` 或 ``assistant`` ,表示消息的角色; ``content`` 则是消息的文本内容。而 ``source`` 字段代表了数据来源,可能包括 ``self-made`` 、 ``alpaca`` 、 ``open-hermes`` 或其他任意字符串。" + +#: ../../source/training/SFT/example.rst:86 9271b908bb19400d8dfe56f1ef0ce1b5 +msgid "" +"To make the jsonl file, you can use ``json`` to save a list of " +"dictionaries to the jsonl file:" +msgstr "你需要用 ``json`` 将一个字典列表存入jsonl文件中:" + +#: ../../source/training/SFT/example.rst:98 6c36700445c340bfa6feeadd6c1bdb1c +msgid "Quickstart" +msgstr "快速开始" + +#: ../../source/training/SFT/example.rst:100 0e86c01757e74bdabfc3bca0e4265481 +msgid "" +"For you to start finetuning quickly, we directly provide a shell script " +"for you to run without paying attention to details. You need " +"different hyperparameters for different types of training, e.g., single-" +"GPU / multi-GPU training, full-parameter tuning, LoRA, or Q-LoRA." +msgstr "为了让您能够快速开始微调,我们直接提供了一个shell脚本,您可以无需关注具体细节即可运行。针对不同类型的训练(例如单GPU训练、多GPU训练、全参数微调、LoRA或Q-LoRA),您可能需要不同的超参数设置。" + +#: ../../source/training/SFT/example.rst:113 6967058d5e504f3f87a084f8b6756224 +msgid "" +"Specify the ```` for your model, ```` for your " +"data, and ```` for your deepspeed configuration. If you use " +"LoRA or Q-LoRA, just add ``--use_lora True`` or ``--q_lora True`` based " +"on your requirements. This is the simplest way to start finetuning. If " +"you want to change more hyperparameters, you can dive into the script and" +" modify those parameters." +msgstr "为您的模型指定 ```` ,为您的数据指定 ```` ,并为您的Deepspeed配置指定 ```` 。如果您使用LoRA或Q-LoRA,只需根据您的需求添加 ``--use_lora True`` 或 ``--q_lora True`` 。这是开始微调的最简单方式。如果您想更改更多超参数,您可以深入脚本并修改这些参数。" + +#: ../../source/training/SFT/example.rst:122 9ce4446fa109470188c3a6f849c51a23 +msgid "Advanced Usages" +msgstr "高级用法" + +#: ../../source/training/SFT/example.rst:124 a5b1894b1348461dae32eafa7193b325 +msgid "" +"In this section, we introduce the details of the scripts, including the " +"core python script as well as the corresponding shell script." +msgstr "在这个部分中,我们介绍python脚本以及shell脚本的相关细节" + +#: ../../source/training/SFT/example.rst:128 7df17cdd0ceb42eb9d7f1734b317c3b9 +msgid "Shell Script" +msgstr "Shell脚本" + +#: ../../source/training/SFT/example.rst:130 9da15ddce8994ea29a9562b498bebb4c +msgid "" +"Before we introduce the python code, we provide a brief introduction to " +"the shell script with commands. We provide some guidance inside the shell" +" script and here we take ``finetune.sh`` as an example." +msgstr "在展示Python代码之前,我们先对包含命令的Shell脚本做一个简单的介绍。我们在Shell脚本中提供了一些指南,并且此处将以 ``finetune.sh`` 这个脚本为例进行解释说明。" + +#: ../../source/training/SFT/example.rst:134 407c05f4ef174a40a986fb9fcc994466 +msgid "" +"To set up the environment variables for distributed training (or single-" +"GPU training), specify the following variables: ``GPUS_PER_NODE``, " +"``NNODES``, ``NODE_RANK``, ``MASTER_ADDR``, and ``MASTER_PORT``. No need " +"to worry too much about them as we provide the default settings for you. " +"In the command, you can pass in the argument ``-m`` and ``-d`` to specify" +" the model path and data path, respectively. You can also pass in the " +"argument ``--deepspeed`` to specify the deepspeed configuration file. We " +"provide two configuration files for ZeRO2 and ZeRO3, and you can choose " +"one based on your requirements. In most cases, we recommend using ZeRO3 " +"for multi-GPU training except for Q-LoRA, where we recommend using ZeRO2." +msgstr "要为分布式训练(或单GPU训练)设置环境变量,请指定以下变量: ``GPUS_PER_NODE`` 、 ``NNODES、NODE_RANK`` 、 ``MASTER_ADDR`` 和 ``MASTER_PORT`` 。不必过于担心这些变量,因为我们为您提供了默认设置。在命令行中,您可以通过传入参数 ``-m`` 和 ``-d`` 来分别指定模型路径和数据路径。您还可以通过传入参数 ``--deepspeed`` 来指定Deepspeed配置文件。我们为您提供针对ZeRO2和ZeRO3的两种配置文件,您可以根据需求选择其中之一。在大多数情况下,我们建议在多GPU训练中使用ZeRO3,但针对Q-LoRA,我们推荐使用ZeRO2。" + +#: ../../source/training/SFT/example.rst:146 3253db51858e4ed9936299f01a35fb8b +msgid "" +"There are a series of hyperparameters to tune. Passing in ``--bf16`` or " +"``--fp16`` to specify the precision for mixed precision training. " +"The other significant hyperparameters include:" +msgstr "有一系列需要调节的超参数。您可以向程序传递 ``--bf16`` 或 ``--fp16`` 参数来指定混合精度训练所采用的精度级别。此外,还有其他一些重要的超参数如下:" + +#: ../../source/training/SFT/example.rst:151 4a971f83ddd140e295c719e1938306b0 +msgid "``--output_dir``: the path of your output models or adapters." +msgstr " ``--output_dir`` :模型或者adapter的输出路径;." + +#: ../../source/training/SFT/example.rst:152 e69801659a8c4bcba41cdcdc4a2fd5fc +msgid "``--num_train_epochs``: the number of training epochs." +msgstr " ``--num_train_epochs`` : 训练轮数;" + +#: ../../source/training/SFT/example.rst:153 7c12854b98524812a8b4760588a62776 +msgid "" +"``--gradient_accumulation_steps``: the number of gradient accumulation " +"steps." +msgstr " ``--gradient_accumulation_steps`` :梯度累积;" + +#: ../../source/training/SFT/example.rst:155 99dce5d00f63497297bcb9f81490803d +msgid "" +"``--per_device_train_batch_size``: the batch size per GPU for training, " +"and the total batch size is equalt to ``per_device_train_batch_size`` " +":math:`\\times` ``number_of_gpus`` :math:`\\times` " +"``gradient_accumulation_steps``." +msgstr " ``--per_device_train_batch_size`` 参数表示每个GPU在训练时的批次大小,而总批次大小等于 ``per_device_train_batch_size`` 乘以 GPU 的数量,再乘以 ``gradient_accumulation_steps`` ;" + +#: ../../source/training/SFT/example.rst:159 475e6a55c72243cb99358dcd2c465910 +msgid "``--learning_rate``: the learning rate." +msgstr " ``--learning_rate`` :学习率;" + +#: ../../source/training/SFT/example.rst:160 d375b81b4a4b450f8204af76a598f07f +msgid "``--warmup_steps``: the number of warmup steps." +msgstr " ``--warmup_steps`` :warmup的步数;" + +#: ../../source/training/SFT/example.rst:161 315ccca447354e63b97336b9c8439317 +msgid "``--lr_scheduler_type``: the type of learning rate scheduler." +msgstr " ``--lr_scheduler_type`` :learning rate scheduler类型;" + +#: ../../source/training/SFT/example.rst:162 338b6abfcb684c87a5c64323712c015e +msgid "``--weight_decay``: the value of weight decay." +msgstr " ``--weight_decay``:weight decay的值;" + +#: ../../source/training/SFT/example.rst:163 092f57e35db9472f80881e60395a6fd9 +msgid "``--adam_beta2``: the value of :math:`\\beta_2` in Adam." +msgstr " ``--adam_beta2`` :Adam :math:`\\beta_2` " + +#: ../../source/training/SFT/example.rst:164 1b3dd161a9e74cbb9d5ea69c7e7e027d +msgid "``--model_max_length``: the maximum sequence length." +msgstr " ``--model_max_length`` :最大长度;" + +#: ../../source/training/SFT/example.rst:165 c8679770b7894a28aae2d37f74fe793b +msgid "" +"``--use_lora``: whether to use LoRA. Adding ``--q_lora`` can enable " +"Q-LoRA." +msgstr " ``--use_lora`` :是否使用LoRA,加上 ``--q_lora`` 即可启用Q-LoRA。"" + +#: ../../source/training/SFT/example.rst:167 19559d935a3a4b5ca489bac858a1a370 +msgid "``--gradient_checkpointing``: whether to use gradient checkpointing." +msgstr " ``--gradient_checkpointing`` :是否使用gradient checkpointing;" + +#: ../../source/training/SFT/example.rst:170 1b7c0668912844a8ac5d659cff28a3ca +msgid "Python Script" +msgstr "Python脚本" + +#: ../../source/training/SFT/example.rst:172 56fefe47f8f84599ad5ef2a3a757b6b9 +msgid "" +"In this script, we mainly use ``trainer`` from HF and ``peft`` to train " +"our models. We also use ``deepspeed`` to accelerate the training process." +" The script is very simple and easy to understand." +msgstr "在本脚本中,我们主要使用来自HF的 ``trainer`` 和 ``peft`` 来训练我们的模型。同时,我们也利用 ``deepspeed`` 来加速训练过程。该脚本非常简洁且易于理解。" + +#: ../../source/training/SFT/example.rst:228 39088ec5d7014e1388276b552acfba08 +msgid "" +"The classes for arguments allow you to specify hyperparameters for model," +" data, training, and additionally LoRA if you use LoRA or Q-LoRA to train" +" your model. Specifically, ``model-max-length`` is a key hyperparameter " +"that determines your maximum sequence length of your training data." +msgstr "参数类允许你为模型、数据和训练指定超参数,如果使用LoRA或Q-LoRA训练模型,还会包含这两个方法的相关超参数。具体来说, ``model-max-length`` 是一个关键的超参数,它决定了训练数据的最大序列长度。" + +#: ../../source/training/SFT/example.rst:234 fe78a42c209d43e2bb6bb05eeef07f6a +msgid "``LoRAArguments`` includes the hyperparameters for LoRA or Q-LoRA:" +msgstr "" + +#: ../../source/training/SFT/example.rst:236 1d4398fa2e54447e9ebab4b86d880a40 +msgid "``lora_r``: the rank for LoRA;" +msgstr " ``LoRAArguments`` 包含了用于LoRA或Q-LoRA的超参数:" + +#: ../../source/training/SFT/example.rst:237 a885bf1a19ab4d05b3d1727b1fe45f23 +msgid "``lora_alpha``: the alpha value for LoRA;" +msgstr " `lora_alpha`` :LoRA的alpha值;" + +#: ../../source/training/SFT/example.rst:238 f77081bd15d440299d74c8fae5b14952 +msgid "``lora_dropout``: the dropout rate for LoRA;" +msgstr " ``lora_dropout`` :LoRA的Dropout;" + +#: ../../source/training/SFT/example.rst:239 ed286b58fe1143a88e18430a2e0faa2a +msgid "" +"``lora_target_modules``: the target modules for LoRA. By default we tune " +"all linear layers;" +msgstr " ``lora_target_modules`` :LoRA的目标模块,默认情况下,我们对所有线性层进行调优;" + +#: ../../source/training/SFT/example.rst:241 245ff8c677174e4b80486a2b7bc54b1e +msgid "``lora_weight_path``: the path to the weight file for LoRA;" +msgstr " ``lora_weight_path``:LoRA的权重路径;" + +#: ../../source/training/SFT/example.rst:242 441ef87612c647518633090a3889360d +msgid "``lora_bias``: the bias for LoRA;" +msgstr " ``lora_bias`` :LoRA的bias" + +#: ../../source/training/SFT/example.rst:243 95776633d70841efb4187ad9408ffb23 +msgid "``q_lora``: whether to use Q-LoRA." +msgstr " ``q_lora`` 是否使用Q-LoRA。"" + +#: ../../source/training/SFT/example.rst:301 8842a7bafb2d4d77a63590bdd79195ce +msgid "" +"The method ``safe_save_model_for_hf_trainer``, which uses " +"``get_peft_state_maybe_zero_3``, helps tackle the problems in saving " +"models trained either with or without ZeRO3." +msgstr "方法 ``safe_save_model_for_hf_trainer`` 通过使用 ``get_peft_state_maybe_zero_3`` 有助于解决在保存采用或未采用ZeRO3技术训练的模型时遇到的问题。" + +#: ../../source/training/SFT/example.rst:335 7850340690ee4a4ebc65de95cd04ccd6 +msgid "" +"For data preprocessing, we use ``preprocess`` to organize the data. " +"Specifically, we apply our ChatML template to the texts. If you prefer " +"other chat templates, you can use others, e.g., by still applying " +"``apply_chat_template()`` with another tokenizer. The chat template is " +"stored in the ``tokenizer_config.json`` in the HF repo. Additionally, we " +"pad the sequence of each sample to the maximum length for training." +msgstr "在数据预处理阶段,我们使用 ``preprocess`` 来整理数据。具体来说,我们应用ChatML模板对文本进行处理。如果您倾向于使用其他chat模板,您也可以选择其他的,例如,仍然通过``apply_chat_template()``函数配合另一个tokenizer进行应用。Chat模板存储在HF仓库中的 ``tokenizer_config.json`` 文件中。此外,我们还将每个样本的序列填充到最大长度,以便于训练。" + +#: ../../source/training/SFT/example.rst:432 c308fd832bd747a48ac896a9ffaa9804 +msgid "" +"Then we utilize ``make_supervised_data_module`` by using " +"``SupervisedDataset`` or ``LazySupervisedDataset`` to build the dataset." +msgstr "然后我们利用 ``make_supervised_data_module`` ,通过使用 ``SupervisedDataset`` 或 ``LazySupervisedDataset`` 来构建数据集。" + +#: ../../source/training/SFT/example.rst:555 2245d0d984224d9dbc8ddbb43160c596 +msgid "" +"The ``train`` method is the key to the training. In general, it loads the" +" tokenizer and model with ``AutoTokenizer.from_pretrained()`` and " +"``AutoModelForCausalLM.from_pretrained()``. If we use LoRA, the method " +"will initialize LoRA configuration with ``LoraConfig``. If we apply " +"Q-LoRA, we should use ``prepare_model_for_kbit_training``. Note that for " +"now it still does not support resume for LoRA. Then we leave the " +"following efforts to ``trainer`` and have a cup of coffee!" +msgstr "``train`` 方法是训练过程的关键所在。通常情况下,它会通过 ``AutoTokenizer.from_pretrained()`` 和 ``AutoModelForCausalLM.from_pretrained()`` 来加载tokenizer和模型。如果使用了LoRA,该方法将会用 ``LoraConfig`` 初始化LoRA配置。若应用Q-LoRA,则应当采用 ``prepare_model_for_kbit_training`` 。请注意,目前还不支持对LoRA的续训(resume)。接下来的任务就交给trainer处理,此时不妨喝杯咖啡稍作休息!" + +#: ../../source/training/SFT/example.rst:564 5224efdee6424eec88b1fdf0a99e4694 +msgid "Next Step" +msgstr "下一步" + +#: ../../source/training/SFT/example.rst:566 2f2432fcec6e42758b92c50f6c7855bd +msgid "" +"Now, you are able to use a very simple script to perform different types " +"of SFT. Alternatively, you can use more advanced training libraries, such" +" as `Axolotl `__ or " +"`LLaMA-Factory `__, to enjoy " +"more functionalities. To take a step forward, after SFT, you can consider" +" RLHF to align your model to human preferences! Stay tuned for our next " +"tutorial on RLHF!" +msgstr "现在,您可以使用一个非常简单的脚本来执行不同类型的SFT。另外,您还可以选择使用更高级的训练库,例如 `Axolotl `__ 或 `LLaMA-Factory `__ ,以享受更多的功能。进一步来说,在完成SFT之后,您可以考虑采用RLHF(强化学习与人类反馈)来使您的模型更好地与人类偏好对齐!请继续关注我们接下来关于RLHF的教程!" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/training/SFT/index.mo b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/index.mo new file mode 100644 index 0000000000000000000000000000000000000000..f8e0c0ae18f00a36579690d8e73a4c09efe5a212 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/index.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/training/SFT/index.po b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/index.po new file mode 100644 index 0000000000000000000000000000000000000000..1cb2af0ff287c0ae34c1c6f9c4008d6d71f9658d --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/index.po @@ -0,0 +1,21 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/training/SFT/index.rst:2 7c5733b15e73491ca46e02dcd6a501f8 +msgid "SFT" +msgstr "有监督微调" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/training/SFT/llama_factory.mo b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/llama_factory.mo new file mode 100644 index 0000000000000000000000000000000000000000..8b3cb8cf9a44b3e9edfe72ad87a8813759c352e7 Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/llama_factory.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/training/SFT/llama_factory.po b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/llama_factory.po new file mode 100644 index 0000000000000000000000000000000000000000..d8d0540e9da24fbd9569d9b0a7b7fc9b0890fd6f --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/training/SFT/llama_factory.po @@ -0,0 +1,181 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-03-12 01:42+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/training/SFT/llama_factory.rst:2 +#: 59f81b6b7fa440c9b569151bd34595fd +msgid "LLaMA-Factory" +msgstr "" + +#: ../../source/training/SFT/llama_factory.rst:4 +#: 1d5a0e9c836a43e984330f7b50e84487 +msgid "" +"Here we provide a script for supervised finetuning Qwen1.5 with `LLaMA-" +"Factory `__. This script for " +"supervised finetuning (SFT) has the following features:" +msgstr "我们将介绍如何使用 `LLaMA-Factory `__ 微调模型。本脚本包含如下特点:" + +#: ../../source/training/SFT/llama_factory.rst:8 +#: ebe5c05bb39346f0b64ef71ec2f2c0a7 +msgid "Support single-GPU and multi-GPU training;" +msgstr "支持单卡和多卡分布式训练" + +#: ../../source/training/SFT/llama_factory.rst:10 +#: 28e8b2797a93491591eff4fcb6f1a4ea +msgid "Support full-parameter tuning, LoRA, Q-LoRA, Dora." +msgstr "支持全参数微调、LoRA、Q-LoRA 和 DoRA 。" + +#: ../../source/training/SFT/llama_factory.rst:12 +#: 5705aea24e634555a9c1ac297415c062 +msgid "In the following, we introduce more details about the usage of the script." +msgstr "下文将介绍更多关于脚本的用法。" + +#: ../../source/training/SFT/llama_factory.rst:16 +#: a946af86f08044379906c17ecafed11a +msgid "Installation" +msgstr "安装" + +#: ../../source/training/SFT/llama_factory.rst:18 +#: 2c970d53e2e04cdc910f62a0b77ed626 +msgid "Before you start, make sure you have installed the following packages:" +msgstr "开始之前,确保你已经安装了以下代码库:" + +#: ../../source/training/SFT/llama_factory.rst:20 +#: 0e3e1ec5879340e98f4e25e4b6d9ded1 +msgid "" +"Follow the instructions of `LLaMA-Factory `__, and build the environment." +msgstr "" +"根据 `LLaMA-Factory `__ " +"官方指引构建好你的环境" + +#: ../../source/training/SFT/llama_factory.rst:23 +#: 166ac903c6ce4285841641f5f3b5bec0 +msgid "Install these packages (Optional):" +msgstr "安装下列代码库(可选):" + +#: ../../source/training/SFT/llama_factory.rst:30 +#: 5092a8b55dba46ca95ac6e177af0fa99 +msgid "" +"If you want to use `FlashAttention-2 `__, make sure your CUDA is 11.6 and above." +msgstr "" +"如你使用 `FlashAttention-2 `__" +" ,请确保你的CUDA版本在11.6以上。" + +#: ../../source/training/SFT/llama_factory.rst:35 +#: ee8e36c067c94af2a4a74238f3d26ac5 +msgid "Data Preparation" +msgstr "准备数据" + +#: ../../source/training/SFT/llama_factory.rst:37 +#: bad133d73f4049459f22f7c2cbf0523e +msgid "" +"LLaMA-Factory provides several training datasets in ``data`` folder, you " +"can use it directly. If you are using a custom dataset, please prepare " +"your dataset as follow." +msgstr "" +"LLaMA-Factory 在 ``data`` " +"文件夹中提供了多个训练数据集,您可以直接使用它们。如果您打算使用自定义数据集,请按照以下方式准备您的数据集。" + +#: ../../source/training/SFT/llama_factory.rst:41 +#: 6d942c4471c448b9a67a327d67442b34 +msgid "" +"Organize your data in a **json** file and put your data in ``data`` " +"folder. LLaMA-Factory supports dataset in ``alpaca`` or ``sharegpt`` " +"format." +msgstr "" +"请将您的数据以 ``json`` 格式进行组织,并将数据放入 data 文件夹中。LLaMA-Factory 支持以 ``alpaca`` 或 " +"``sharegpt`` 格式的数据集。" + +#: ../../source/training/SFT/llama_factory.rst:45 +#: c80fd006f8bf481f806582eb000215e8 +msgid "The dataset in ``alpaca`` format should follow the below format:" +msgstr "``alpaca`` 格式的数据集应遵循以下格式:" + +#: ../../source/training/SFT/llama_factory.rst:62 +#: 876409cf2a294398926fdcbe355fd4d9 +msgid "The dataset in ``sharegpt`` format should follow the below format:" +msgstr "``sharegpt`` 格式的数据集应遵循以下格式:" + +#: ../../source/training/SFT/llama_factory.rst:83 +#: 3731a5252e4749efb1f5b897934094a7 +msgid "" +"Provide your dataset definition in ``data/dataset_info.json`` in the " +"following format ." +msgstr "在 ``data/dataset_info.json`` 文件中提供您的数据集定义,并采用以下格式:" + +#: ../../source/training/SFT/llama_factory.rst:86 +#: c048531148ff496dba3e8f57feb11e34 +msgid "" +"For ``alpaca`` format dataset, the columns in ``dataset_info.json`` " +"should be:" +msgstr "对于 ``alpaca`` 格式的数据集,其 ``dataset_info.json`` 文件中的列应为:" + +#: ../../source/training/SFT/llama_factory.rst:102 +#: 6ece984e56c4463a80b71f8af62282fe +msgid "" +"For ``sharegpt`` format dataset, the columns in ``dataset_info.json`` " +"should be:" +msgstr "对于 ``sharegpt`` 格式的数据集,``dataset_info.json`` 文件中的列应该包括:" + +#: ../../source/training/SFT/llama_factory.rst:124 +#: 6da6d3f24fcf46ef86a08820e79446dd +msgid "Training" +msgstr "训练" + +#: ../../source/training/SFT/llama_factory.rst:126 +#: f3a81032d0924cb9b7dacdad9b32b4fc +msgid "Execute the following training command:" +msgstr "执行下列命令:" + +#: ../../source/training/SFT/llama_factory.rst:166 +#: fc83cc671a04458db38f7ac6d3fee22b +msgid "" +"and enjoy the training process. To make changes to your training, you can" +" modify the arguments in the training command to adjust the " +"hyperparameters. One argument to note is ``cutoff_len``, which is the " +"maximum length of the training data. Control this parameter to avoid OOM " +"error." +msgstr "" +"并享受训练过程。若要调整您的训练,您可以通过修改训练命令中的参数来调整超参数。其中一个需要注意的参数是 ``cutoff_len`` " +",它代表训练数据的最大长度。通过控制这个参数,可以避免出现OOM(内存溢出)错误。" + +#: ../../source/training/SFT/llama_factory.rst:173 +#: 663c9bd983754ac0aa20bd1dbb524598 +msgid "Merge LoRA" +msgstr "合并LoRA" + +#: ../../source/training/SFT/llama_factory.rst:175 +#: 845a8a06b9494e589ee21b5c7ebaf22d +msgid "" +"If you train your model with LoRA, you probably need to merge adapter " +"parameters to the main branch. Run the following command to perform the " +"merging of LoRA adapters." +msgstr "如果你使用 LoRA 训练模型,可能需要将adapter参数合并到主分支中。请运行以下命令以执行 LoRA adapter 的合并操作。" + +#: ../../source/training/SFT/llama_factory.rst:191 +#: 03fd595a678f48cabe5b9c6192edc406 +msgid "Conclusion" +msgstr "结语" + +#: ../../source/training/SFT/llama_factory.rst:193 +#: 3e566cad14514beaad47a28f282ada51 +msgid "" +"The above content is the simplest way to use LLaMA-Factory to train Qwen." +" Feel free to dive into the details by checking the official repo!" +msgstr "上述内容是使用LLaMA-Factory训练Qwen的最简单方法。 欢迎通过查看官方仓库深入了解详细信息!" + diff --git a/docs/locales/zh_CN/LC_MESSAGES/web_ui/text_generation_webui.mo b/docs/locales/zh_CN/LC_MESSAGES/web_ui/text_generation_webui.mo new file mode 100644 index 0000000000000000000000000000000000000000..452aeedc752fe9ad876444668535770964a609ad Binary files /dev/null and b/docs/locales/zh_CN/LC_MESSAGES/web_ui/text_generation_webui.mo differ diff --git a/docs/locales/zh_CN/LC_MESSAGES/web_ui/text_generation_webui.po b/docs/locales/zh_CN/LC_MESSAGES/web_ui/text_generation_webui.po new file mode 100644 index 0000000000000000000000000000000000000000..7818a91906c7a6a7cbeb9ed68e8da89628521bd1 --- /dev/null +++ b/docs/locales/zh_CN/LC_MESSAGES/web_ui/text_generation_webui.po @@ -0,0 +1,113 @@ +# Copyright (C) 2024, Qwen Team, Alibaba Group. +# This file is distributed under the same license as the Qwen package. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Qwen \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-02-21 21:08+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Language: zh_CN\n" +"Language-Team: zh_CN \n" +"Plural-Forms: nplurals=1; plural=0;\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.14.0\n" + +#: ../../source/web_ui/text_generation_webui.rst:2 +#: c0f23ae236e54e24af7deef5d7146003 +msgid "Text Generation Web UI" +msgstr "Text Generation Web UI" + +#: ../../source/web_ui/text_generation_webui.rst:4 +#: 47af3df3d9ab4729846c3a0d6d0895b5 +msgid "" +"`Text Generation Web UI `__ (TGW, or usually referred to “oobabooga”) is a popular web UI " +"for text generation, similar to `AUTOMATIC1111/stable-diffusion-webui " +"`__. It has " +"multiple interfaces, and supports multiple model backends, including " +"`Transformers `__, " +"`llama.cpp `__ (through `llama-" +"cpp-python `__), `ExLlamaV2 " +"`__, `AutoGPTQ " +"`__, `AutoAWQ `__, `GPTQ-for-LLaMa " +"`__, `CTransformers " +"`__, `QuIP# `__. In this section, we introduce how to run" +" Qwen locally with TGW." +msgstr "`Text Generation Web UI `__ (简称TGW,通常被称为“oobabooga”)是一款流行的文本生成Web界面工具,类似于 `AUTOMATIC1111/stable-diffusion-webui `__ 。它拥有多个交互界面,并支持多种模型后端,包括 `Transformers `__ 、 `llama.cpp `__ (通过 `llama-cpp-python `__ 实现)、 `ExLlamaV2 `__ 、 `AutoGPTQ `__ 、 `AutoAWQ `__ 、 `GPTQ-for-LLaMa `__ 、 `CTransformers `__ 以及 `QuIP# `__ 。在本节中,我们将介绍如何在本地环境中使用TGW运行Qwen。" + +#: ../../source/web_ui/text_generation_webui.rst:23 +#: 5e9eb228343a4168b8c1af490096093e +msgid "Quickstart" +msgstr "快速开始" + +#: ../../source/web_ui/text_generation_webui.rst:25 +#: 17dd3e7a101d448c8f382b0f7bc96a63 +msgid "" +"The simplest way to run TGW is to use the provided shell scripts in the " +"`repo `__. For the " +"first step, clone the repo and enter the directory:" +msgstr "最简单的运行TGW(Text Generation WebUI)的方法是使用 `repo `__ 中提供的Shell脚本。首先,克隆repo并进去文件夹中:" + +#: ../../source/web_ui/text_generation_webui.rst:34 +#: 009d1688050543bfb6bc4863646e78d3 +msgid "" +"You can directly run the ``start_linux.sh``, ``start_windows.bat``, " +"``start_macos.sh``, or ``start_wsl.bat`` script depending on your OS. " +"Alternatively you can manually install the requirements in your conda " +"environment. Here I take the practice on MacOS as an example." +msgstr "你可以根据你的操作系统直接运行相应的脚本,例如在Linux系统上运行 ``start_linux.sh`` ,在Windows系统上运行 ``start_windows.bat`` ,在MacOS系统上运行 ``start_macos.sh`` ,或者在Windows子系统Linux(WSL)上运行 ``start_wsl.bat`` 。另外,你也可以选择手动在conda环境中安装所需的依赖项。这里以MacOS系统为例进行实践操作。" + +#: ../../source/web_ui/text_generation_webui.rst:45 +#: c8d93c382166438f943c1ae4b9d84be3 +msgid "" +"Then you can install the requirements by running ``pip install -r`` based" +" on your OS, e.g.," +msgstr "接下来,您可以根据您的操作系统执行 ``pip install -r`` 命令来安装相应的依赖项,例如," + +#: ../../source/web_ui/text_generation_webui.rst:52 +#: 52b5cbf125f442b699dc05bf827ecb5f +msgid "" +"For ``bitsandbytes`` and ``llama-cpp-python`` inside the requirements, I " +"advise you to install them through ``pip`` directly. However, temporarily" +" please do not use GGUF as the performance with TGW is unsatisfactory. " +"After finishing the installation of required packages, you need to " +"prepare your models by putting the model files or directories in the " +"folder ``./models``. For example, you should put the transformers model " +"directory of ``Qwen1.5-7B-Chat`` in the way shown below:" +msgstr "对于requirements中的 ``bitsandbytes`` 和 ``llama-cpp-python`` ,我建议您直接通过 ``pip`` 进行安装。但是,暂时请不要使用GGUF,因为其与TGW配合时的性能表现不佳。在完成所需包的安装之后,您需要准备模型,将模型文件或目录放在``./models``文件夹中。例如,您应按照以下方式将``transformers``模型目录 ``Qwen1.5-7B-Chat`` 放置到相应位置。例如,您应该将 ``Qwen1.5-7B-Chat`` 模型的目录结构放入 ``./models`` 文件夹内。" + +#: ../../source/web_ui/text_generation_webui.rst:76 +#: 3d7582c62c0348cb90d4c221f4b7ad33 +msgid "Then you just need to run" +msgstr "随后你需要运行" + +#: ../../source/web_ui/text_generation_webui.rst:82 +#: 040a0472b9d34ef7a9f7854f57f6cd62 +msgid "to launch your web UI service. Please browse to" +msgstr "来启动你的网页服务。请点击进入" + +#: ../../source/web_ui/text_generation_webui.rst:88 +#: 8118d325bcee4f1aa52d63cd8208f6a2 +msgid "and enjoy playing with Qwen in a web UI!" +msgstr "然后享受使用Qwen的Web UI吧!" + +#: ../../source/web_ui/text_generation_webui.rst:91 +#: 453dec3129ea4a60b6c803dd6c43c251 +msgid "Next Step" +msgstr "下一步" + +#: ../../source/web_ui/text_generation_webui.rst:93 +#: cc02078a24ff484b8494356ced5ee451 +msgid "" +"There are a lot more usages in TGW, where you can even enjoy role play, " +"use different types of quantized models, train LoRA, incorporate " +"extensions like stable diffusion and whisper, etc. Go to figure out more " +"advanced usages and apply them to Qwen models!" +msgstr "TGW 中包含了许多更多用途,您甚至可以在其中享受角色扮演的乐趣,并使用不同类型的量化模型。您可以训练诸如LoRA这样的算法,并将Stable Diffusion和Whisper等扩展功能纳入其中。赶快去探索更多高级用法,并将它们应用于Qwen模型中吧!" + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..061f32f91b96f05f8fa2b52b2edcdcc19aa33d50 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=source +set BUILDDIR=build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.https://www.sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt new file mode 100644 index 0000000000000000000000000000000000000000..e38c3ae959ab51a48d646de2f8388bcfe458bfa4 --- /dev/null +++ b/docs/requirements-docs.txt @@ -0,0 +1,4 @@ +sphinx +sphinx-book-theme +sphinx-copybutton +furo diff --git a/docs/source/assets/.DS_Store b/docs/source/assets/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..8f74faefd5183de2611aed5e0b8eaf755b075931 Binary files /dev/null and b/docs/source/assets/.DS_Store differ diff --git a/docs/source/assets/logo/.DS_Store b/docs/source/assets/logo/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 Binary files /dev/null and b/docs/source/assets/logo/.DS_Store differ diff --git a/docs/source/assets/logo/qwen1.5.png b/docs/source/assets/logo/qwen1.5.png new file mode 100644 index 0000000000000000000000000000000000000000..d979501da28d89bc4857ca29187335a1251fd204 Binary files /dev/null and b/docs/source/assets/logo/qwen1.5.png differ diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..87ca11b38484cc0e9d949af9306440734f52ba82 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,112 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. + +import os +import sys +from sphinx.ext import autodoc +import logging + +sys.path.insert(0, os.path.abspath(os.path.join('..', '..'))) + +logger = logging.getLogger(__name__) + +# -- Project information ----------------------------------------------------- + +project = 'Qwen' +copyright = '2024, Qwen Team' +author = 'Qwen Team' + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", + "sphinx.ext.intersphinx", + # "sphinx_copybutton", + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + +# Exclude the prompt "$" when copying code +copybutton_prompt_text = r"\$ " +copybutton_prompt_is_regexp = True + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_title = project +html_theme = 'furo' +# html_logo = 'assets/logo/qwen.png' +# html_theme_options = { +# 'path_to_docs': 'docs/source', +# 'repository_url': 'https://github.com/QwenLM/Qwen1.5', +# # 'use_repository_button': True, +# } +html_sidebars = { + "**": [ + "sidebar/scroll-start.html", + "sidebar/brand.html", + "sidebar/navigation.html", + "sidebar/ethical-ads.html", + "sidebar/scroll-end.html", + ] +} + +# multi-language docs +language = 'en' +locale_dirs = ['../locales/'] # path is example but recommended. +gettext_compact = False # optional. +gettext_uuid = True # optional. + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +# html_static_path = ['_static'] + +# Mock out external dependencies here. +autodoc_mock_imports = [ + "torch", "transformers" +] + +for mock_target in autodoc_mock_imports: + if mock_target in sys.modules: + logger.info( + f"Potentially problematic mock target ({mock_target}) found; " + "autodoc_mock_imports cannot mock modules that have already " + "been loaded into sys.modules when the sphinx build starts.") + + +class MockedClassDocumenter(autodoc.ClassDocumenter): + """Remove note about base class when a class is derived from object.""" + + def add_line(self, line: str, source: str, *lineno: int) -> None: + if line == " Bases: :py:class:`object`": + return + super().add_line(line, source, *lineno) + + +autodoc.ClassDocumenter = MockedClassDocumenter + +navigation_with_keys = False \ No newline at end of file diff --git a/docs/source/deployment/vllm.rst b/docs/source/deployment/vllm.rst new file mode 100644 index 0000000000000000000000000000000000000000..30fd96eb3c2d718d3444f8f37178e779c4ba7ed9 --- /dev/null +++ b/docs/source/deployment/vllm.rst @@ -0,0 +1,206 @@ +vLLM +===================== + +We recommend you trying with +`vLLM `__ for your deployement +of Qwen. It is simple to use, and it is fast with state-of-the-art +serving throughtput, efficienct management of attention key value memory +with PagedAttention, continuous batching of input requests, optimized +CUDA kernels, etc. To learn more about vLLM, please refer to the +`paper `__ and +`documentation `__. + +Installation +------------ + +By default, you can install ``vLLM`` by pip: +``pip install vLLM>=0.3.0``, but if you are using CUDA 11.8, check the +note in the official document for installation +(`link `__) +for some help. We also advise you to install ray by ``pip install ray`` +for distributed serving. + +Offline Batched Inference +------------------------- + +Models supported by Qwen2 codes, e.g., Qwen1.5, are supported by vLLM. +The simplest usage of vLLM is offline batched inference as demonstrated +below. + +.. code:: python + + from transformers import AutoTokenizer + from vllm import LLM, SamplingParams + + # Initialize the tokenizer + tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-7B-Chat") + + # Pass the default decoding hyperparameters of Qwen1.5-7B-Chat + # max_tokens is for the maximum length for generation. + sampling_params = SamplingParams(temperature=0.7, top_p=0.8, repetition_penalty=1.05, max_tokens=512) + + # Input the model name or path. Can be GPTQ or AWQ models. + llm = LLM(model="Qwen/Qwen1.5-7B-Chat") + + # Prepare your prompts + prompt = "Tell me something about large language models." + messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": prompt} + ] + text = tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + + # generate outputs + outputs = llm.generate([text], sampling_params) + + # Print the outputs. + for output in outputs: + prompt = output.prompt + generated_text = output.outputs[0].text + print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") + +OpenAI-API Compatible API Service +--------------------------------- + +It is easy to build an OpenAI-API compatible API service with vLLM, +which can be deployed as a server that implements OpenAI API protocol. +By default, it starts the server at ``http://localhost:8000``. You can +specify the address with ``--host`` and ``--port`` arguments. Run the +command as shown below: + +.. code:: bash + + python -m vllm.entrypoints.openai.api_server \ + --model Qwen/Qwen1.5-7B-Chat + +You don’t need to worry about chat template as it by default uses the +chat template provided by the tokenizer. + +Then, you can use the `create chat +interface `__ +to communicate with Qwen: + +.. code:: bash + + curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{ + "model": "Qwen/Qwen1.5-7B-Chat", + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."} + ] + }' + +or you can use python client with ``openai`` python package as shown +below: + +.. code:: python + + from openai import OpenAI + # Set OpenAI's API key and API base to use vLLM's API server. + openai_api_key = "EMPTY" + openai_api_base = "http://localhost:8000/v1" + + client = OpenAI( + api_key=openai_api_key, + base_url=openai_api_base, + ) + + chat_response = client.chat.completions.create( + model="Qwen/Qwen1.5-7B-Chat", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."}, + ] + ) + print("Chat response:", chat_response) + +Multi-GPU Distributred Serving +------------------------------ + +To scale up your serving throughputs, distributed serving helps you by +leveraging more GPU devices. Besides, for large models like +``Qwen1.5-72B-Chat``, it is impossible to serve it on a single GPU. +Here, we demonstrate how to run ``Qwen1.5-72B-Chat`` with tensor +parallelism just by passing in the argument ``tensor_parallel_size``: + +.. code:: python + + from vllm import LLM, SamplingParams + llm = LLM(model="Qwen/Qwen1.5-72B-Chat", tensor_parallel_size=4) + +You can run multi-GPU serving by passing in the argument +``--tensor-parallel-size``: + +.. code:: bash + + python -m vllm.entrypoints.api_server \ + --model Qwen/Qwen1.5-72B-Chat \ + --tensor-parallel-size 4 + +Serving Quantized Models +------------------------ + +vLLM supports different types of quantized models, including AWQ, GPTQ, +SqueezeLLM, etc. Here we show how to deploy AWQ and GPTQ models. The +usage is almost the same as above except for an additional argument for +quantization. For example, to run an AWQ model. e.g., +``Qwen1.5-7B-Chat-AWQ``: + +.. code:: python + + from vllm import LLM, SamplingParams + llm = LLM(model="Qwen/Qwen1.5-7B-Chat-AWQ", quantization="awq") + +or GPTQ models like ``Qwen1.5-7B-Chat-GPTQ-Int8``: + +.. code:: python + + llm = LLM(model="Qwen/Qwen1.5-7B-Chat-GPTQ-Int4", quantization="gptq") + +Similarly, you can run serving adding the argument ``--quantization`` as +shown below: + +.. code:: bash + + python -m vllm.entrypoints.openai.api_server \ + --model Qwen/Qwen1.5-7B-Chat-AWQ \ + --quantization awq + +or + +.. code:: bash + + python -m vllm.entrypoints.openai.api_server \ + --model Qwen/Qwen1.5-7B-Chat-GPTQ-Int8 \ + --quantization gptq + +Additionally, vLLM supports the combination of AWQ or GPTQ models with +KV cache quantization, namely FP8 E5M2 KV Cache. For example: + +.. code:: python + + llm = LLM(model="Qwen/Qwen1.5-7B-Chat-GPTQ-Int8", quantization="gptq", kv_cache_dtype="fp8_e5m2") + +.. code:: bash + + python -m vllm.entrypoints.openai.api_server \ + --model Qwen/Qwen1.5-7B-Chat-GPTQ-Int8 \ + --quantization gptq \ + --kv-cache-dtype fp8_e5m2 + +Troubleshooting +--------------- + +You may encounter OOM issues that are pretty annoying. We recommend two +arguments for you to make some fix. The first one is +``--max-model-len``. Our provided default ``max_postiion_embedding`` is +``32768`` and thus the maximum length for the serving is also this +value, leading to higher requirements of memory. Reducing it to a proper +length for yourself often helps with the OOM issue. Another argument you +can pay attention to is ``--gpu-memory-utilization``. By default it is +``0.9`` and you can level it up to tackle the OOM problem. This is also +why you find a vLLM service always takes so much memory. diff --git a/docs/source/framework/function_call.rst b/docs/source/framework/function_call.rst new file mode 100644 index 0000000000000000000000000000000000000000..bd89221bd931497ae4cbf2d556cfb3a7b2e75e3d --- /dev/null +++ b/docs/source/framework/function_call.rst @@ -0,0 +1,131 @@ +Function Calling +================ + +We offer a wrapper for function calling over the dashscope API and the +OpenAI API in `Qwen-Agent `__. + +Use Case +-------- + +.. code:: py + + import json + import os + from qwen_agent.llm import get_chat_model + + + # Example dummy function hard coded to return the same weather + # In production, this could be your backend API or an external API + def get_current_weather(location, unit='fahrenheit'): + """Get the current weather in a given location""" + if 'tokyo' in location.lower(): + return json.dumps({ + 'location': 'Tokyo', + 'temperature': '10', + 'unit': 'celsius' + }) + elif 'san francisco' in location.lower(): + return json.dumps({ + 'location': 'San Francisco', + 'temperature': '72', + 'unit': 'fahrenheit' + }) + elif 'paris' in location.lower(): + return json.dumps({ + 'location': 'Paris', + 'temperature': '22', + 'unit': 'celsius' + }) + else: + return json.dumps({'location': location, 'temperature': 'unknown'}) + + + def test(): + llm = get_chat_model({ + # Use the model service provided by DashScope: + 'model': 'qwen-max', + 'model_server': 'dashscope', + 'api_key': os.getenv('DASHSCOPE_API_KEY'), + + # Use the model service provided by Together.AI: + # 'model': 'Qwen/Qwen1.5-14B-Chat', + # 'model_server': 'https://api.together.xyz', # api_base + # 'api_key': os.getenv('TOGETHER_API_KEY'), + + # Use your own model service compatible with OpenAI API: + # 'model': 'Qwen/Qwen1.5-72B-Chat', + # 'model_server': 'http://localhost:8000/v1', # api_base + # 'api_key': 'EMPTY', + }) + + # Step 1: send the conversation and available functions to the model + messages = [{ + 'role': 'user', + 'content': "What's the weather like in San Francisco?" + }] + functions = [{ + 'name': 'get_current_weather', + 'description': 'Get the current weather in a given location', + 'parameters': { + 'type': 'object', + 'properties': { + 'location': { + 'type': 'string', + 'description': + 'The city and state, e.g. San Francisco, CA', + }, + 'unit': { + 'type': 'string', + 'enum': ['celsius', 'fahrenheit'] + }, + }, + 'required': ['location'], + }, + }] + + print('# Assistant Response 1:') + responses = [] + for responses in llm.chat(messages=messages, + functions=functions, + stream=True): + print(responses) + + messages.extend(responses) # extend conversation with assistant's reply + + # Step 2: check if the model wanted to call a function + last_response = messages[-1] + if last_response.get('function_call', None): + + # Step 3: call the function + # Note: the JSON response may not always be valid; be sure to handle errors + available_functions = { + 'get_current_weather': get_current_weather, + } # only one function in this example, but you can have multiple + function_name = last_response['function_call']['name'] + function_to_call = available_functions[function_name] + function_args = json.loads(last_response['function_call']['arguments']) + function_response = function_to_call( + location=function_args.get('location'), + unit=function_args.get('unit'), + ) + print('# Function Response:') + print(function_response) + + # Step 4: send the info for each function call and function response to the model + messages.append({ + 'role': 'function', + 'name': function_name, + 'content': function_response, + }) # extend conversation with function response + + print('# Assistant Response 2:') + for responses in llm.chat( + messages=messages, + functions=functions, + stream=True, + ): # get a new response from the model where it can see the function response + print(responses) + + + if __name__ == '__main__': + test() diff --git a/docs/source/framework/qwen_agent.rst b/docs/source/framework/qwen_agent.rst new file mode 100644 index 0000000000000000000000000000000000000000..ae3fa1d63c253ef3b62969d5364e17260b28b1ee --- /dev/null +++ b/docs/source/framework/qwen_agent.rst @@ -0,0 +1,93 @@ +Qwen-Agent +========== + +`Qwen-Agent `__ is a framework for +developing LLM applications based on the instruction following, tool +usage, planning, and memory capabilities of Qwen. It also comes with +example applications such as Browser Assistant, Code Interpreter, and +Custom Assistant. + +Installation +------------ + +.. code:: bash + + git clone https://github.com/QwenLM/Qwen-Agent.git + cd Qwen-Agent + pip install -e ./ + +Developing Your Own Agent +------------------------- + +Qwen-Agent provides atomic components such as LLMs and prompts, as well +as high-level components such as Agents. The example below uses the +Assistant component as an illustration, demonstrating how to add custom +tools and quickly develop an agent that uses tools. + +.. code:: py + + import json + import os + + import json5 + import urllib.parse + from qwen_agent.agents import Assistant + from qwen_agent.tools.base import BaseTool, register_tool + + llm_cfg = { + # Use the model service provided by DashScope: + 'model': 'qwen-max', + 'model_server': 'dashscope', + # 'api_key': 'YOUR_DASHSCOPE_API_KEY', + # It will use the `DASHSCOPE_API_KEY' environment variable if 'api_key' is not set here. + + # Use your own model service compatible with OpenAI API: + # 'model': 'Qwen/Qwen1.5-72B-Chat', + # 'model_server': 'http://localhost:8000/v1', # api_base + # 'api_key': 'EMPTY', + + # (Optional) LLM hyperparameters for generation: + 'generate_cfg': { + 'top_p': 0.8 + } + } + system = 'According to the user\'s request, you first draw a picture and then automatically run code to download the picture ' + \ + 'and select an image operation from the given document to process the image' + + # Add a custom tool named my_image_gen: + @register_tool('my_image_gen') + class MyImageGen(BaseTool): + description = 'AI painting (image generation) service, input text description, and return the image URL drawn based on text information.' + parameters = [{ + 'name': 'prompt', + 'type': 'string', + 'description': 'Detailed description of the desired image content, in English', + 'required': True + }] + + def call(self, params: str, **kwargs) -> str: + prompt = json5.loads(params)['prompt'] + prompt = urllib.parse.quote(prompt) + return json.dumps( + {'image_url': f'https://image.pollinations.ai/prompt/{prompt}'}, + ensure_ascii=False) + + + tools = ['my_image_gen', 'code_interpreter'] # code_interpreter is a built-in tool in Qwen-Agent + bot = Assistant(llm=llm_cfg, + system_message=system, + function_list=tools, + files=[os.path.abspath('doc.pdf')]) + + messages = [] + while True: + query = input('user question: ') + messages.append({'role': 'user', 'content': query}) + response = [] + for response in bot.run(messages=messages): + print('bot response:', response) + messages.extend(response) + +The framework also provides more atomic components for developers to +combine. For additional showcases, please refer to +`examples `__. diff --git a/docs/source/getting_started/installation.rst b/docs/source/getting_started/installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..05fd91628f2c54888cbde3e2ec30c72d37d93cec --- /dev/null +++ b/docs/source/getting_started/installation.rst @@ -0,0 +1,24 @@ +Installation +============ + +To get a quick start with Qwen1.5, you can install the ``transformers`` +library from Hugging Face and use models in the `Qwen1.5 +collection `__. +We advise you to install the latest ``transformers`` or at least version +4.37.0. + +Install with Pip +~~~~~~~~~~~~~~~~ + +.. code:: bash + + pip install transformers + +Install with Conda +~~~~~~~~~~~~~~~~~~ + +.. code:: bash + + conda install conda-forge::transformers + +We advise you to use Python 3.8 or higher, and Pytorch 2.0 or higher. diff --git a/docs/source/getting_started/quickstart.rst b/docs/source/getting_started/quickstart.rst new file mode 100644 index 0000000000000000000000000000000000000000..4ec880a209744c909572ffb3b552545a377e2278 --- /dev/null +++ b/docs/source/getting_started/quickstart.rst @@ -0,0 +1,146 @@ +Quickstart +========== + +This guide helps you quickly start using Qwen1.5. We provide examples of +`Hugging Face Transformers `__ +as well as `ModelScope `__, and +`vLLM `__ for deployment. + +Hugging Face Transformers & ModelScope +-------------------------------------- + +To get a quick start with Qwen1.5, we advise you to try with the +inference with ``transformers`` first. Make sure that you have installed +``transformers>=4.37.0``. The following is a very simple code snippet +showing how to run Qwen1.5-Chat, with an example of Qwen1.5-7B-Chat: + +.. code:: python + + from transformers import AutoModelForCausalLM, AutoTokenizer + device = "cuda" # the device to load the model onto + + # Now you do not need to add "trust_remote_code=True" + model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen1.5-7B-Chat", + torch_dtype="auto", + device_map="auto" + ) + tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-7B-Chat") + + # Instead of using model.chat(), we directly use model.generate() + # But you need to use tokenizer.apply_chat_template() to format your inputs as shown below + prompt = "Give me a short introduction to large language model." + messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": prompt} + ] + text = tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + model_inputs = tokenizer([text], return_tensors="pt").to(device) + + # Directly use generate() and tokenizer.decode() to get the output. + # Use `max_new_tokens` to control the maximum output length. + generated_ids = model.generate( + model_inputs.input_ids, + max_new_tokens=512 + ) + generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) + ] + + response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] + +Previously, we use ``model.chat()`` (see ``modeling_qwen.py`` in +previous Qwen models for more information). Now, we follow the practice +of ``transformers`` and directly use ``model.generate()`` with +``apply_chat_template()`` in tokenizer. + +To tackle with downloading issues, we advise you to try with from +ModelScope, just changing the first line of code above to the following: + +.. code:: python + + from modelscope import AutoModelForCausalLM, AutoTokenizer + +Streaming mode for model chat is simple with the help of +``TextStreamer``. Below we show you an example of how to use it: + +.. code:: python + + ... + # Reuse the code before `model.generate()` in the last code snippet + from transformers import TextStreamer + streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) + generated_ids = model.generate( + model_inputs.input_ids, + max_new_tokens=512, + streamer=streamer, + ) + +vLLM for Deployment +------------------- + +To deploy Qwen1.5, we advise you to use vLLM. vLLM is a fast +and easy-to-use framework for LLM inference and serving. In the +following, we demonstrate how to build a OpenAI-API compatible API +service with vLLM. + +First, make sure you have installed ``vLLM>=0.3.0``: + +.. code:: bash + + pip install vllm + +Run the following code to build up a vllm service. Here we take +Qwen1.5-7B-Chat as an example: + +.. code:: bash + + python -m vllm.entrypoints.openai.api_server --model Qwen/Qwen1.5-7B-Chat + +Then, you can use the `create chat +interface `__ +to communicate with Qwen: + +.. code:: bash + + curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{ + "model": "Qwen/Qwen1.5-7B-Chat", + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."} + ], + }' + +or you can use python client with ``openai`` python package as shown +below: + +.. code:: python + + from openai import OpenAI + # Set OpenAI's API key and API base to use vLLM's API server. + openai_api_key = "EMPTY" + openai_api_base = "http://localhost:8000/v1" + + client = OpenAI( + api_key=openai_api_key, + base_url=openai_api_base, + ) + + chat_response = client.chat.completions.create( + model="Qwen/Qwen1.5-7B-Chat", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."}, + ] + ) + print("Chat response:", chat_response) + +Next Step +--------- + +Now, you can have fun with Qwen models. Would love to know more about +its usages? Feel free to check other documents in this documentation. diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..216afee6bc1de5797a2cbbdecc356eadce1a3916 --- /dev/null +++ b/docs/source/index.rst @@ -0,0 +1,93 @@ +.. Qwen documentation master file, created by + sphinx-quickstart on Tue Feb 20 21:16:41 2024. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to Qwen! +================ + +.. figure:: ./assets/logo/qwen1.5.png + :width: 60% + :align: center + :alt: Qwen + :class: no-scaled-link + + +Qwen is the large language model and large multimodal model series of the Qwen Team, Alibaba Group. Now the large language models have been upgraded to Qwen1.5. Both language models and multimodal models are pretrained on large-scale multilingual and multimodal data and post-trained on quality data for aligning to human preferences. +Qwen is capable of natural language understanding, text generation, vision understanding, audio understanding, tool use, role play, playing as AI agent, etc. + +The latest version, Qwen1.5, has the following features: + +* 6 model sizes, including 0.5B, 1.8B, 4B, 7B, 14B, and 72B; +* Base and chat models for each size, with the chat models aligned for human preferences; +* Multilingual support of both base and chat models; +* Stable support of 32K context length for models of all sizes +* Supporting tool use, RAG, role play, and playing as AI agent; + +For more information, please visit our: + +* `Blog `__ +* `GitHub `__ +* `Hugging Face `__ +* `ModelScope `__ +* `Qwen1.5 Collection `__ + +Join our community by joining our `Discord `__ and `WeChat `__ group. We are looking forward to seeing you there! + + + +Documentation +------------- + +.. toctree:: + :maxdepth: 1 + :caption: Getting Started + + getting_started/installation + getting_started/quickstart + +.. toctree:: + :maxdepth: 1 + :caption: Inference + + inference/chat + +.. toctree:: + :maxdepth: 1 + :caption: Run Locally + + run_locally/llama.cpp + run_locally/ollama + +.. toctree:: + :maxdepth: 1 + :caption: Web UI + + web_ui/text_generation_webui + +.. toctree:: + :maxdepth: 1 + :caption: Quantization + + quantization/awq + quantization/gptq + quantization/gguf + +.. toctree:: + :maxdepth: 1 + :caption: Deployment + + deployment/vllm + +.. toctree:: + :maxdepth: 2 + :caption: Training + + training/SFT/index + +.. toctree:: + :maxdepth: 1 + :caption: Framework + + framework/qwen_agent + framework/function_call diff --git a/docs/source/inference/chat.rst b/docs/source/inference/chat.rst new file mode 100644 index 0000000000000000000000000000000000000000..240af6151d38482a2b6be6592e9fc57b9a4b6257 --- /dev/null +++ b/docs/source/inference/chat.rst @@ -0,0 +1,115 @@ +Using Transformers to Chat +========================== + +The most significant but also the simplest usage of Qwen1.5 is to chat +with it using the ``transformers`` library. In this document, we show +how to chat with ``Qwen1.5-7B-Chat``, in either streaming mode or not. + +Basic Usage +----------- + +You can just write several lines of code with ``transformers`` to chat with +Qwen1.5-Chat. Essentially, we build the tokenizer and the model with +``from_pretrained`` method, and we use ``generate`` method to perform +chatting with the help of chat template provided by the tokenizer. +Below is an example of how to chat with Qwen1.5-7B-Chat: + +.. code:: python + + from transformers import AutoModelForCausalLM, AutoTokenizer + device = "cuda" # the device to load the model onto + + # Now you do not need to add "trust_remote_code=True" + model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen1.5-7B-Chat", + torch_dtype="auto", + device_map="auto" + ) + tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-7B-Chat") + + # Instead of using model.chat(), we directly use model.generate() + # But you need to use tokenizer.apply_chat_template() to format your inputs as shown below + prompt = "Give me a short introduction to large language model." + messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": prompt} + ] + text = tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + model_inputs = tokenizer([text], return_tensors="pt").to(device) + + # Directly use generate() and tokenizer.decode() to get the output. + # Use `max_new_tokens` to control the maximum output length. + generated_ids = model.generate( + model_inputs.input_ids, + max_new_tokens=512 + ) + generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) + ] + + response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] + +Note that the previous method in the original Qwen repo ``chat()`` is +now replaced by ``generate()``. The ``apply_chat_template()`` function +is used to convert the messages into a format that the model can +understand. The ``add_generation_prompt`` argument is used to add a +generation prompt, which refers to ``<|im_start|>assistant\n`` to the input. +Notably, we apply ChatML template for chat models following our previous +practice. The ``max_new_tokens`` argument is used to set the maximum length +of the response. The ``tokenizer.batch_decode()`` function is used to +decode the response. In terms of the input, the above ``messages`` is an +example to show how to format your dialog history and system prompt. By +default, if you do not specify system prompt, we directly use ``You are +a helpful assistant.``. + +Streaming Mode +-------------- + +With the help of ``TextStreamer``, you can modify your chatting with +Qwen to streaming mode. Below we show you an example of how to use it: + +.. code:: python + + # Repeat the code above before model.generate() + # Starting here, we add streamer for text generation. + from transformers import TextStreamer + streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) + + # This will print the output in the streaming mode. + generated_ids = model.generate( + model_inputs, + max_new_tokens=512, + streamer=streamer, + ) + +Besides using ``TextStreamer``, we can also use ``TextIteratorStreamer`` +which stores print-ready text in a queue, to be used by a downstream +application as an iterator: + +.. code:: python + + # Repeat the code above before model.generate() + # Starting here, we add streamer for text generation. + from transformers import TextIteratorStreamer + streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) + + from threading import Thread + generation_kwargs = dict(model_inputs, streamer=streamer, max_new_tokens=512) + thread = Thread(target=model.generate, kwargs=generation_kwargs) + + thread.start() + generated_text = "" + for new_text in streamer: + generated_text += new_text + print(generated_text) + +Next Step +--------- + +Now you can chat with Qwen1.5 in either streaming mode or not. Continue +to read the documentation and try to figure out more advanced usages of +model inference! diff --git a/docs/source/quantization/awq.rst b/docs/source/quantization/awq.rst new file mode 100644 index 0000000000000000000000000000000000000000..5d3fe457d893256d77225c0e36ae7ba7634fa68f --- /dev/null +++ b/docs/source/quantization/awq.rst @@ -0,0 +1,172 @@ +AWQ +===================== + +For quantized models, one of our recommendations is the usage of +`AWQ `__ with +`AutoAWQ `__. AWQ refers to +Activation-aware Weight Quantization, a hardware-friendly approach for +LLM low-bit weight-only quantization. AutoAWQ is an easy-to-use package +for 4-bit quantized models. AutoAWQ speeds up models by 3x and reduces +memory requirements by 3x compared to FP16. AutoAWQ implements the +Activation-aware Weight Quantization (AWQ) algorithm for quantizing +LLMs. In this document, we show you how to use the quantized model with +Transformers and also how to quantize your own model. + +Usage of AWQ Quantized Models with Transformers +----------------------------------------------- + +Now, Transformers has officially supported AutoAWQ, which means that you +can directly use the quantized model with Transformers. The following is +a very simple code snippet showing how to run ``Qwen1.5-7B-Chat-AWQ`` +with the quantized model: + +.. code:: python + + from transformers import AutoModelForCausalLM, AutoTokenizer + device = "cuda" # the device to load the model onto + + model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen1.5-7B-Chat-AWQ", # the quantized model + device_map="auto" + ) + tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-7B-Chat-AWQ") + + prompt = "Give me a short introduction to large language model." + messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": prompt} + ] + text = tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + model_inputs = tokenizer([text], return_tensors="pt").to(device) + + generated_ids = model.generate( + model_inputs.input_ids, + max_new_tokens=512 + ) + generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) + ] + + response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] + +Usage of AWQ Quantized Models with vLLM +--------------------------------------- + +vLLM has supported AWQ, which means that you can directly use our +provided AWQ models or those trained with ``AutoAWQ`` with vLLM. +Actually, the usage is the same with the basic usage of vLLM. We provide +a simple example of how to launch OpenAI-API compatible API with vLLM +and ``Qwen1.5-7B-Chat-AWQ``: + +.. code:: bash + + python -m vllm.entrypoints.openai.api_server --model Qwen/Qwen1.5-7B-Chat-AWQ + +.. code:: bash + + curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{ + "model": "Qwen/Qwen1.5-7B-Chat-AWQ", + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."} + ], + }' + +or you can use python client with ``openai`` python package as shown +below: + +.. code:: python + + from openai import OpenAI + # Set OpenAI's API key and API base to use vLLM's API server. + openai_api_key = "EMPTY" + openai_api_base = "http://localhost:8000/v1" + + client = OpenAI( + api_key=openai_api_key, + base_url=openai_api_base, + ) + + chat_response = client.chat.completions.create( + model="Qwen/Qwen1.5-7B-Chat-AWQ", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."}, + ] + ) + print("Chat response:", chat_response) + +Quantize Your Own Model with AutoAWQ +------------------------------------ + +If you want to quantize your own model to AWQ quantized models, we +advise you to use AutoAWQ. It is suggested installing the latest version +of the package by installing from source code: + +.. code:: bash + + git clone https://github.com/casper-hansen/AutoAWQ.git + cd AutoAWQ + pip install -e . + +Suppose you have finetuned a model based on ``Qwen1.5-7B``, which is +named ``Qwen1.5-7B-finetuned``, with your own dataset, e.g., Alpaca. To +build your own AWQ quantized model, you need to use the training data +for calibration. Below, we provide a simple demonstration for you to +run: + +.. code:: python + + from awq import AutoAWQForCausalLM + from transformers import AutoTokenizer + + # Specify paths and hyperparameters for quantization + model_path = "your_model_path" + quant_path = "your_quantized_model_path" + quant_config = { "zero_point": True, "q_group_size": 128, "w_bit": 4, "version": "GEMM" } + + # Load your tokenizer and model with AutoAWQ + tokenizer = AutoTokenizer.from_pretrained(model_path) + model = AutoAWQForCausalLM.from_pretrained(model_path, device_map="auto", safetensors=True) + +Then you need to prepare your data for calibaration. What you need to do +is just put samples into a list, each of which is a text. As we directly +use our finetuning data for calibration, we first format it with ChatML +template. For example: + +.. code:: python + + data = [] + for msg in messages: + msg = c['messages'] + text = tokenizer.apply_chat_template(msg, tokenize=False, add_generation_prompt=False) + data.append(text.strip()) + +where each ``msg`` is a typical chat message as shown below: + +.. code:: json + + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me who you are."}, + {"role": "assistant", "content": "I am a large language model named Qwen..."} + ] + +Then just run the calibration process by one line of code: + +.. code:: python + + model.quantize(tokenizer, quant_config=quant_config, calib_data=data) + +Finally, save the quantized model: + +.. code:: python + + model.save_quantized(quant_path, safetensors=True, shard_size="4GB") + tokenizer.save_pretrained(quant_path) + +Then you can obtain your own AWQ quantized model for deployment. Enjoy! diff --git a/docs/source/quantization/gguf.rst b/docs/source/quantization/gguf.rst new file mode 100644 index 0000000000000000000000000000000000000000..dccca13f81bb62fe4bc20815cc13e196e7101140 --- /dev/null +++ b/docs/source/quantization/gguf.rst @@ -0,0 +1,87 @@ +GGUF +=========================== + +Recently, running LLMs locally is popular in the community, and running +GGUF files with llama.cpp is a typical example. With llama.cpp, you can +not only build GGUF files for your models but also perform low-bit +quantization. In GGUF, you can directly quantize your models without +calibration, or apply the AWQ scale for better quality, or use imatrix +with calibration data. In this document, we demonstrate the simplest way +to quantize your model as well as the way to apply AWQ scale to your +Qwen model quantization. + +Quantize Your Models and Make GGUF Files +---------------------------------------- + +Before you move to quantization, make sure you have followed the +instruction and started to use llama.cpp. The following guidance will +NOT provide instructions about installation and building. Now, suppose +you would like to quantize ``Qwen1.5-7B-Chat``. You need to first make a +GGUF file for the fp16 model as shown below: + +.. code:: bash + + python convert-hf-to-gguf.py Qwen/Qwen1.5-7B-Chat --outfile models/7B/qwen1_5-7b-chat-fp16.gguf + +where the first argument refers to the path to the HF model directory or +the HF model name, and the second argument refers to the path of your +output GGUF file (here I just put it under the directory ``models/7B``. +Remember to create the directory before you run the command). In this +way, you have generated a GGUF file for your fp16 model, and you then +need to quantize it to low bits based on your requirements. An example +of quantizing the model to 4 bits is shown below: + +.. code:: bash + + ./quantize models/7B/qwen1_5-7b-chat-fp16.gguf models/7B/qwen1_5-7b-chat-q4_0.gguf q4_0 + +where we use ``q4_0`` for the 4-bit quantization. Until now, you have +finished quantizing a model to 4 bits and putting it into a GGUF file, +which can be run directly with llama.cpp. + +Quantize Your Models With AWQ Scales +------------------------------------ + +To improve the quality of your quantized models, one possible solution +is to apply the AWQ scale, following `this +script `__. +First of all, when you run ``model.quantize()`` with AutoAWQ, remember +to add ``export_compatible=True`` as shown below: + +.. code:: python + + ... + model.quantize( + tokenizer, + quant_config=quant_config, + export_compatible=True + ) + model.save_pretrained(quant_path) + ... + +With ``model.save_quantzed()`` as shown above, a fp16 model with AWQ +scales is saved. Then, when you run ``convert-hf-to-gguf.py``, remember +to replace the model path with the path to the fp16 model with AWQ +scales, e.g., + +.. code:: bash + + python convert-hf-to-gguf.py ${quant_path} --outfile models/7B/qwen1_5-7b-chat-fp16-awq.gguf + +In this way, you can apply the AWQ scales to your quantized models in +GGUF formats, which helps improving the model quality. + +We usually quantize the fp16 model to 2, 3, 4, 5, 6, and 8-bit models. +To perform different low-bit quantization, just replace the quantization +method in your command. For example, if you want to quantize your model +to 2-bit model, you can replace ``q4_0`` to ``q2_k`` as demonstrated +below: + +.. code:: bash + + ./quantize models/7B/qwen1_5-7b-chat-fp16.gguf models/7B/qwen1_5-7b-chat-q2_k.gguf q2_k + +We now provide GGUF models in the following quantization levels: +``q2_k``, ``q3_k_m``, ``q4_0``, ``q4_k_m``, ``q5_0``, ``q5_k_m``, +``q6_k``, and ``q8_0``. For more information, please visit +`llama.cpp `__. diff --git a/docs/source/quantization/gptq.rst b/docs/source/quantization/gptq.rst new file mode 100644 index 0000000000000000000000000000000000000000..2b90d60ecac34fbc3328c94037c1d62cc82930d0 --- /dev/null +++ b/docs/source/quantization/gptq.rst @@ -0,0 +1,189 @@ +GPTQ +====================== + +`GPTQ `__ is a quantization method for +GPT-like LLMs, which uses one-shot weight quantization based on +approximate second-order information. In this document, we show you how +to use the quantized model with transformers and also how to quantize +your own model with `AutoGPTQ `__. + +Usage of GPTQ Models with Transformers +-------------------------------------- + +Now, Transformers has officially supported AutoGPTQ, which means that +you can directly use the quantized model with Transformers. The +following is a very simple code snippet showing how to run +``Qwen1.5-7B-Chat-GPTQ-Int8`` (note that for each size of Qwen1.5, we +provide both Int4 and Int8 quantized models) with the quantized model: + +.. code:: python + + from transformers import AutoModelForCausalLM, AutoTokenizer + device = "cuda" # the device to load the model onto + + model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen1.5-7B-Chat-GPTQ-Int8", # the quantized model + device_map="auto" + ) + tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-7B-Chat-GPTQ-Int8") + + prompt = "Give me a short introduction to large language model." + messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": prompt} + ] + text = tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + model_inputs = tokenizer([text], return_tensors="pt").to(device) + + generated_ids = model.generate( + model_inputs.input_ids, + max_new_tokens=512 + ) + generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) + ] + + response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] + +Usage of GPTQ Quantized Models with vLLM +---------------------------------------- + +vLLM has supported GPTQ, which means that you can directly use our +provided GPTQ models or those trained with ``AutoGPTQ`` with vLLM. +Actually, the usage is the same with the basic usage of vLLM. We provide +a simple example of how to launch OpenAI-API compatible API with vLLM +and ``Qwen1.5-7B-Chat-GPTQ-Int8``: + +.. code:: bash + + python -m vllm.entrypoints.openai.api_server --model Qwen/Qwen1.5-7B-Chat-GPTQ-Int8 + +.. code:: bash + + curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{ + "model": "Qwen/Qwen1.5-7B-Chat-GPTQ-Int8", + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."} + ], + }' + +or you can use python client with ``openai`` python package as shown +below: + +.. code:: python + + from openai import OpenAI + # Set OpenAI's API key and API base to use vLLM's API server. + openai_api_key = "EMPTY" + openai_api_base = "http://localhost:8000/v1" + + client = OpenAI( + api_key=openai_api_key, + base_url=openai_api_base, + ) + + chat_response = client.chat.completions.create( + model="Qwen/Qwen1.5-7B-Chat-GPTQ-Int8", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me something about large language models."}, + ] + ) + print("Chat response:", chat_response) + +Quantize Your Own Model with AutoGPTQ +------------------------------------- + +If you want to quantize your own model to GPTQ quantized models, we +advise you to use AutoGPTQ. It is suggested installing the latest +version of the package by installing from source code: + +.. code:: bash + + git clone https://github.com/AutoGPTQ/AutoGPTQ + cd AutoGPTQ + pip install -e . + +Suppose you have finetuned a model based on ``Qwen1.5-7B``, which is +named ``Qwen1.5-7B-finetuned``, with your own dataset, e.g., Alpaca. To +build your own GPTQ quantized model, you need to use the training data +for calibration. Below, we provide a simple demonstration for you to +run: + +.. code:: python + + from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig + from transformers import AutoTokenizer + + # Specify paths and hyperparameters for quantization + model_path = "your_model_path" + quant_path = "your_quantized_model_path" + quantize_config = BaseQuantizeConfig( + bits=8, # 4 or 8 + group_size=128, + damp_percent=0.01, + desc_act=False, # set to False can significantly speed up inference but the perplexity may slightly bad + static_groups=False, + sym=True, + true_sequential=True, + model_name_or_path=None, + model_file_base_name="model" + ) + max_len = 8192 + + # Load your tokenizer and model with AutoGPTQ + # To learn about loading model to multiple GPUs, + # visit https://github.com/AutoGPTQ/AutoGPTQ/blob/main/docs/tutorial/02-Advanced-Model-Loading-and-Best-Practice.md + tokenizer = AutoTokenizer.from_pretrained(model_path) + model = AutoGPTQForCausalLM.from_pretrained(model_path, safetensors=True) + +Then you need to prepare your data for calibaration. What you need to do +is just put samples into a list, each of which is a text. As we directly +use our finetuning data for calibration, we first format it with ChatML +template. For example: + +.. code:: python + + data = [] + for msg in messages: + msg = c['messages'] + text = tokenizer.apply_chat_template(msg, tokenize=False, add_generation_prompt=False) + model_inputs = tokenizer([text]) + input_ids = torch.tensor(model_inputs.input_ids[:max_len], dtype=torch.int) + data.append(dict(input_ids=input_ids, attention_mask=input_ids.ne(tokenizer.pad_token_id))) + +where each ``msg`` is a typical chat message as shown below: + +.. code:: json + + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Tell me who you are."}, + {"role": "assistant", "content": "I am a large language model named Qwen..."} + ] + +Then just run the calibration process by one line of code: + +.. code:: python + + logging.basicConfig( + format="%(asctime)s %(levelname)s [%(name)s] %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S" + ) + model.quantize(data, cache_examples_on_gpu=False) + +Finally, save the quantized model: + +.. code:: python + + model.save_quantized(quant_path, use_safetensors=True) + tokenizer.save_pretrained(quant_path) + +It is unfortunate that the ``save_quantized`` method does not support +sharding. For sharding, you need to load the model and use +``save_pretrained`` from transformers to save and shard the model. +Except for this, everything is so simple. Enjoy! diff --git a/docs/source/run_locally/llama.cpp.rst b/docs/source/run_locally/llama.cpp.rst new file mode 100644 index 0000000000000000000000000000000000000000..4e5ff95a7697606235d76e1557da167d991ed1e6 --- /dev/null +++ b/docs/source/run_locally/llama.cpp.rst @@ -0,0 +1,113 @@ +llama.cpp +=========================== + +`llama.cpp `__ is a C++ library +for LLM inference with mimimal setup. It enables running Qwen on your +local machine. It is a plain C/C++ implementation without dependencies, +and it has AVX, AVX2 and AVX512 support for x86 architectures. It +provides 2, 3, 4, 5, 6, and 8-bit quantization for faster inference and +reduced memory footprint. CPU+GPU hybrid inference to partially +accelerate models larger than the total VRAM capacity is also supported. +Essentially, the usage of llama.cpp is to run the GGUF (GPT-Generated +Unified Format ) models. For more information, please refer to the +official GitHub repo. Here we demonstrate how to run Qwen with +llama.cpp. + +Prerequisites +------------- + +This example is for the usage on Linux or MacOS. For the first step, +clone the repo and enter the directory: + +.. code:: bash + + git clone https://github.com/ggerganov/llama.cpp + cd llama.cpp + +Then use ``make``: + +.. code:: bash + + make + +Then you can run GGUF files with ``llama.cpp``. + +Running Qwen GGUF Files +----------------------- + +We provide a series of GGUF models in our Hugging Face organization, and +to search for what you need you can search the repo names with +``-GGUF``. Download the GGUF model that you want with +``huggingface-cli`` (you need to install it first with +``pip install huggingface_hub``): + +.. code:: bash + + huggingface-cli download --local-dir --local-dir-use-symlinks False + +for example: + +.. code:: bash + + huggingface-cli download Qwen/Qwen1.5-7B-Chat-GGUF qwen1_5-7b-chat-q5_k_m.gguf --local-dir . --local-dir-use-symlinks False + +Then you can run the model with the following command: + +.. code:: bash + + ./main -m qwen1_5-7b-chat-q5_k_m.gguf -n 512 --color -i -cml -f prompts/chat-with-qwen.txt + +where ``-n`` refers to the maximum number of tokens to generate. There +are other hyperparameters for you to choose and you can run + +.. code:: bash + + ./main -h + +to figure them out. + +Make Your GGUF Files +-------------------- + +We introduce the method of creating and quantizing GGUF files in +`quantization/llama.cpp <../quantization/gguf.html>`__. You can refer +to that document for more information. + +Perplexity Evaluation +--------------------- + +``llama.cpp`` provides methods for us to evaluate the perplexity +performance of the GGUF models. To do this, you need to prepare the +dataset, say "wiki test". Here we demonstrate an example to run the +test. + +For the first step, download the dataset: + +.. code:: bash + + wget https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research -O wikitext-2-raw-v1.zip + unzip wikitext-2-raw-v1.zip + +Then you can run the test with the following command: + +.. code:: bash + + ./perplexity -m models/7B/ggml-model-q4_0.gguf -f wiki.test.raw + +where the output is like + +.. code:: text + + perplexity : calculating perplexity over 655 chunks + 24.43 seconds per pass - ETA 4.45 hours + [1]4.5970,[2]5.1807,[3]6.0382,... + +Wait for some time and you will get the perplexity of the model. + +Use GGUF with LM Studio +----------------------- + +If you still find it difficult to use ``llama.cpp``, I advise you to +play with `LM Studio `__, which is a platform +for your to search and run local LLMs. Qwen1.5 has already been +officially part of LM Studio. Have fun! diff --git a/docs/source/run_locally/ollama.rst b/docs/source/run_locally/ollama.rst new file mode 100644 index 0000000000000000000000000000000000000000..a3d39cbafde143b10c5be568d94a6cd44aa23685 --- /dev/null +++ b/docs/source/run_locally/ollama.rst @@ -0,0 +1,71 @@ +Ollama +=========================== + +`Ollama `__ helps you run LLMs locally with only a +few commands. It is available at MacOS, Linux, and Windows. Now, Qwen1.5 +is officially on Ollama, and you can run it with one command: + +.. code:: bash + + ollama run qwen + +Next, we introduce more detailed usages of Ollama for running Qwen +models. + +Quickstart +---------- + +Visit the official website `Ollama `__ and click +download to install Ollama on your device. You can also search models in +the website, where you can find the Qwen1.5 models. Except for the +default one, you can choose to run Qwen1.5-Chat models of different +sizes by: + +- ``ollama run qwen:0.5b`` +- ``ollama run qwen:1.8b`` +- ``ollama run qwen:4b`` +- ``ollama run qwen:7b`` +- ``ollama run qwen:14b`` +- ``ollama run qwen:72b`` + +Run Ollama with Your GGUF Files +------------------------------- + +Sometimes you don't want to pull models and you just want to use Ollama +with your own GGUF files. Suppose you have a GGUF file of Qwen, +``qwen1_5-7b-chat-q4_0.gguf``. For the first step, you need to create a +file called ``Modelfile``. The content of the file is shown below: + +.. code:: text + + FROM qwen1_5-7b-chat-q4_0.gguf + + # set the temperature to 1 [higher is more creative, lower is more coherent] + PARAMETER temperature 0.7 + PARAMETER top_p 0.8 + PARAMETER repeat_penalty 1.05 + PARAMETER top_k 20 + + TEMPLATE """{{ if and .First .System }}<|im_start|>system + {{ .System }}<|im_end|> + {{ end }}<|im_start|>user + {{ .Prompt }}<|im_end|> + <|im_start|>assistant + {{ .Response }}""" + + # set the system message + SYSTEM """ + You are a helpful assistant. + """ + +Then create the ollama model by running: + +.. code:: bash + + ollama create qwen7b -f Modelfile + +Once it is finished, you can run your ollama model by: + +.. code:: bash + + ollama run qwen7b diff --git a/docs/source/training/SFT/example.rst b/docs/source/training/SFT/example.rst new file mode 100644 index 0000000000000000000000000000000000000000..a60f2a657142e787481184db766632ad889a81be --- /dev/null +++ b/docs/source/training/SFT/example.rst @@ -0,0 +1,572 @@ +Example +==================================================== + +Here we provide a very simple script for supervised finetuning, which is revised from the training +script in ```Fastchat`` `__. The +script is used to finetune Qwen with Hugging Face Trainer. You can check +the script +`here `__. This +script for supervised finetuning (SFT) has the following features: + +- Support single-GPU and multi-GPU training; +- Support full-parameter tuning, + `LoRA `__, and + `Q-LoRA `__. + +In the following, we introduce more details about the usage of the +script. + +Installation +------------ + +Before you start, make sure you have installed the following packages: + +.. code:: bash + + pip install peft deepspeed optimum accelerate + +Data Preparation +---------------- + +For data preparation, we advise you to organize the data in a jsonl +file, where each line is a dictionary as demonstrated below: + +.. code:: json + + { + "type": "chatml", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Tell me something about large language models." + }, + { + "role": "assistant", + "content": "Large language models are a type of language model that is trained on a large corpus of text data. They are capable of generating human-like text and are used in a variety of natural language processing tasks..." + } + ], + "source": "unknown" + } + +.. code:: json + + { + "type": "chatml", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "What is your name?" + }, + { + "role": "assistant", + "content": "My name is Qwen." + } + ], + "source": "self-made" + } + +Above are two examples of each data sample in the dataset. Each sample +is a JSON object with the following fields: ``type``, ``messages`` and +``source``. ``messages`` is required while the others are optional for +you to label your data format and data source. The ``messages`` field is +a list of JSON objects, each of which has two fields: ``role`` and +``content``. ``role`` can be ``system``, ``user``, or ``assistant``. +``content`` is the text of the message. ``source`` is the source of the +data, which can be ``self-made``, ``alpaca``, ``open-hermes``, or any +other string. + +To make the jsonl file, you can use ``json`` to save a list of +dictionaries to the jsonl file: + +.. code:: python + + import json + + with open('data.jsonl', 'w') as f: + for sample in samples: + f.write(json.dumps(sample) + '\n') + +Quickstart +---------- + +For you to start finetuning quickly, we directly provide a shell script +for you to run without paying attention to details. You need +different hyperparameters for different types of training, e.g., +single-GPU / multi-GPU training, full-parameter tuning, LoRA, or Q-LoRA. + + + +.. code:: bash + + cd examples/sft + bash finetune.sh -m -d --deepspeed [--use_lora True] [--q_lora True] + + +Specify the ```` for your model, ```` for your +data, and ```` for your deepspeed configuration. +If you use LoRA or Q-LoRA, just add ``--use_lora True`` or +``--q_lora True`` based on your requirements. +This is the simplest way to start finetuning. If you want to change more +hyperparameters, you can dive into the script and modify those +parameters. + +Advanced Usages +--------------- + +In this section, we introduce the details of the scripts, including the +core python script as well as the corresponding shell script. + +Shell Script +~~~~~~~~~~~~~ + +Before we introduce the python code, we provide a brief introduction to +the shell script with commands. We provide some guidance inside the +shell script and here we take ``finetune.sh`` as an example. + +To set up the environment variables for distributed training (or +single-GPU training), specify the following variables: +``GPUS_PER_NODE``, ``NNODES``, ``NODE_RANK``, ``MASTER_ADDR``, and +``MASTER_PORT``. No need to worry too much about them as we provide the +default settings for you. In the command, you can pass in the argument +``-m`` and ``-d`` to specify the model path and data path, respectively. +You can also pass in the argument ``--deepspeed`` to specify the +deepspeed configuration file. We provide two configuration files for +ZeRO2 and ZeRO3, and you can choose one based on your requirements. In +most cases, we recommend using ZeRO3 for multi-GPU training except for +Q-LoRA, where we recommend using ZeRO2. + +There are a series of hyperparameters to tune. Passing in ``--bf16`` or +``--fp16`` to specify the precision for mixed precision training. +The other significant hyperparameters include: + +- ``--output_dir``: the path of your output models or adapters. +- ``--num_train_epochs``: the number of training epochs. +- ``--gradient_accumulation_steps``: the number of gradient + accumulation steps. +- ``--per_device_train_batch_size``: the batch size per GPU for + training, and the total batch size is equalt to + ``per_device_train_batch_size`` :math:`\times` ``number_of_gpus`` + :math:`\times` ``gradient_accumulation_steps``. +- ``--learning_rate``: the learning rate. +- ``--warmup_steps``: the number of warmup steps. +- ``--lr_scheduler_type``: the type of learning rate scheduler. +- ``--weight_decay``: the value of weight decay. +- ``--adam_beta2``: the value of :math:`\beta_2` in Adam. +- ``--model_max_length``: the maximum sequence length. +- ``--use_lora``: whether to use LoRA. Adding ``--q_lora`` can enable + Q-LoRA. +- ``--gradient_checkpointing``: whether to use gradient checkpointing. + +Python Script +~~~~~~~~~~~~~ + +In this script, we mainly use ``trainer`` from HF and ``peft`` to train +our models. We also use ``deepspeed`` to accelerate the training +process. The script is very simple and easy to understand. + +.. code:: python + + @dataclass + @dataclass + class ModelArguments: + model_name_or_path: Optional[str] = field(default="Qwen/Qwen-7B") + + + @dataclass + class DataArguments: + data_path: str = field( + default=None, metadata={"help": "Path to the training data."} + ) + eval_data_path: str = field( + default=None, metadata={"help": "Path to the evaluation data."} + ) + lazy_preprocess: bool = False + + + @dataclass + class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + model_max_length: int = field( + default=8192, + metadata={ + "help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)." + }, + ) + use_lora: bool = False + + + @dataclass + class LoraArguments: + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_target_modules: List[str] = field( + default_factory=lambda: [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "up_proj", + "gate_proj", + "down_proj", + ] + ) + lora_weight_path: str = "" + lora_bias: str = "none" + q_lora: bool = False + +The classes for arguments allow you to specify hyperparameters for +model, data, training, and additionally LoRA if you use LoRA or Q-LoRA +to train your model. Specifically, ``model-max-length`` is a key +hyperparameter that determines your maximum sequence length of your +training data. + +``LoRAArguments`` includes the hyperparameters for LoRA or Q-LoRA: + +- ``lora_r``: the rank for LoRA; +- ``lora_alpha``: the alpha value for LoRA; +- ``lora_dropout``: the dropout rate for LoRA; +- ``lora_target_modules``: the target modules for LoRA. By default we + tune all linear layers; +- ``lora_weight_path``: the path to the weight file for LoRA; +- ``lora_bias``: the bias for LoRA; +- ``q_lora``: whether to use Q-LoRA. + + +.. code:: python + + def maybe_zero_3(param): + if hasattr(param, "ds_id"): + assert param.ds_status == ZeroParamStatus.NOT_AVAILABLE + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + + # Borrowed from peft.utils.get_peft_model_state_dict + def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v) for k, v in to_return.items()} + return to_return + + + def safe_save_model_for_hf_trainer( + trainer: transformers.Trainer, output_dir: str, bias="none" + ): + """Collects the state dict and dump to disk.""" + # check if zero3 mode enabled + if deepspeed.is_deepspeed_zero3_enabled(): + state_dict = trainer.model_wrapped._zero3_consolidated_16bit_state_dict() + else: + if trainer.args.use_lora: + state_dict = get_peft_state_maybe_zero_3( + trainer.model.named_parameters(), bias + ) + else: + state_dict = trainer.model.state_dict() + if trainer.args.should_save and trainer.args.local_rank == 0: + trainer._save(output_dir, state_dict=state_dict) + +The method ``safe_save_model_for_hf_trainer``, which uses +``get_peft_state_maybe_zero_3``, helps tackle the problems in saving +models trained either with or without ZeRO3. + +.. code:: python + + def preprocess( + messages, + tokenizer: transformers.PreTrainedTokenizer, + max_len: int, + ) -> Dict: + """Preprocesses the data for supervised fine-tuning.""" + + texts = [] + for i, msg in enumerate(messages): + texts.append( + tokenizer.apply_chat_template( + msg, + tokenize=True, + add_generation_prompt=False, + padding=True, + max_length=max_len, + truncation=True, + ) + ) + input_ids = torch.tensor(texts, dtype=torch.int) + target_ids = input_ids.clone() + target_ids[target_ids == tokenizer.pad_token_id] = IGNORE_TOKEN_ID + attention_mask = input_ids.ne(tokenizer.pad_token_id) + + return dict( + input_ids=input_ids, target_ids=target_ids, attention_mask=attention_mask + ) + +For data preprocessing, we use ``preprocess`` to organize the data. +Specifically, we apply our ChatML template to the texts. If you prefer +other chat templates, you can use others, e.g., by still applying +``apply_chat_template()`` with another tokenizer. The chat template is +stored in the ``tokenizer_config.json`` in the HF repo. Additionally, we +pad the sequence of each sample to the maximum length for training. + +.. code:: python + + class SupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" + + def __init__( + self, raw_data, tokenizer: transformers.PreTrainedTokenizer, max_len: int + ): + super(SupervisedDataset, self).__init__() + + rank0_print("Formatting inputs...") + messages = [example["messages"] for example in raw_data] + data_dict = preprocess(messages, tokenizer, max_len) + + self.input_ids = data_dict["input_ids"] + self.target_ids = data_dict["target_ids"] + self.attention_mask = data_dict["attention_mask"] + + def __len__(self): + return len(self.input_ids) + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + return dict( + input_ids=self.input_ids[i], + labels=self.labels[i], + attention_mask=self.attention_mask[i], + ) + + + class LazySupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" + + def __init__( + self, raw_data, tokenizer: transformers.PreTrainedTokenizer, max_len: int + ): + super(LazySupervisedDataset, self).__init__() + self.tokenizer = tokenizer + self.max_len = max_len + + rank0_print("Formatting inputs...Skip in lazy mode") + self.tokenizer = tokenizer + self.raw_data = raw_data + self.cached_data_dict = {} + + def __len__(self): + return len(self.raw_data) + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + if i in self.cached_data_dict: + return self.cached_data_dict[i] + + ret = preprocess([self.raw_data[i]["messages"]], self.tokenizer, self.max_len) + ret = dict( + input_ids=ret["input_ids"][0], + labels=ret["target_ids"][0], + attention_mask=ret["attention_mask"][0], + ) + self.cached_data_dict[i] = ret + + return ret + + + def make_supervised_data_module( + tokenizer: transformers.PreTrainedTokenizer, + data_args, + max_len, + ) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + dataset_cls = ( + LazySupervisedDataset if data_args.lazy_preprocess else SupervisedDataset + ) + rank0_print("Loading data...") + + train_data = [] + with open(data_args.data_path, "r") as f: + for line in f: + train_data.append(json.loads(line)) + train_dataset = dataset_cls(train_data, tokenizer=tokenizer, max_len=max_len) + + if data_args.eval_data_path: + eval_data = [] + with open(data_args.eval_data_path, "r") as f: + for line in f: + eval_data.append(json.loads(line)) + eval_dataset = dataset_cls(eval_data, tokenizer=tokenizer, max_len=max_len) + else: + eval_dataset = None + + return dict(train_dataset=train_dataset, eval_dataset=eval_dataset) + +Then we utilize ``make_supervised_data_module`` by using +``SupervisedDataset`` or ``LazySupervisedDataset`` to build the dataset. + +.. code:: python + + def train(): + global local_rank + + parser = transformers.HfArgumentParser( + (ModelArguments, DataArguments, TrainingArguments, LoraArguments) + ) + ( + model_args, + data_args, + training_args, + lora_args, + ) = parser.parse_args_into_dataclasses() + + # This serves for single-gpu qlora. + if ( + getattr(training_args, "deepspeed", None) + and int(os.environ.get("WORLD_SIZE", 1)) == 1 + ): + training_args.distributed_state.distributed_type = DistributedType.DEEPSPEED + + local_rank = training_args.local_rank + + device_map = None + world_size = int(os.environ.get("WORLD_SIZE", 1)) + ddp = world_size != 1 + if lora_args.q_lora: + device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)} if ddp else "auto" + if len(training_args.fsdp) > 0 or deepspeed.is_deepspeed_zero3_enabled(): + logging.warning("FSDP or ZeRO3 is incompatible with QLoRA.") + + model_load_kwargs = { + "low_cpu_mem_usage": not deepspeed.is_deepspeed_zero3_enabled(), + } + + compute_dtype = ( + torch.float16 + if training_args.fp16 + else (torch.bfloat16 if training_args.bf16 else torch.float32) + ) + + # Load model and tokenizer + config = transformers.AutoConfig.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + ) + config.use_cache = False + + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, + config=config, + cache_dir=training_args.cache_dir, + device_map=device_map, + quantization_config=BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=compute_dtype, + ) + if training_args.use_lora and lora_args.q_lora + else None, + **model_load_kwargs, + ) + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right", + use_fast=False, + ) + + if training_args.use_lora: + lora_config = LoraConfig( + r=lora_args.lora_r, + lora_alpha=lora_args.lora_alpha, + target_modules=lora_args.lora_target_modules, + lora_dropout=lora_args.lora_dropout, + bias=lora_args.lora_bias, + task_type="CAUSAL_LM", + ) + if lora_args.q_lora: + model = prepare_model_for_kbit_training( + model, use_gradient_checkpointing=training_args.gradient_checkpointing + ) + + model = get_peft_model(model, lora_config) + + # Print peft trainable params + model.print_trainable_parameters() + + if training_args.gradient_checkpointing: + model.enable_input_require_grads() + + # Load data + data_module = make_supervised_data_module( + tokenizer=tokenizer, data_args=data_args, max_len=training_args.model_max_length + ) + + # Start trainer + trainer = Trainer( + model=model, tokenizer=tokenizer, args=training_args, **data_module + ) + + # `not training_args.use_lora` is a temporary workaround for the issue that there are problems with + # loading the checkpoint when using LoRA with DeepSpeed. + # Check this issue https://github.com/huggingface/peft/issues/746 for more information. + if ( + list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")) + and not training_args.use_lora + ): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + trainer.save_state() + + safe_save_model_for_hf_trainer( + trainer=trainer, output_dir=training_args.output_dir, bias=lora_args.lora_bias + ) + +The ``train`` method is the key to the training. In general, it loads +the tokenizer and model with ``AutoTokenizer.from_pretrained()`` and +``AutoModelForCausalLM.from_pretrained()``. If we use LoRA, the method +will initialize LoRA configuration with ``LoraConfig``. If we apply +Q-LoRA, we should use ``prepare_model_for_kbit_training``. Note that for +now it still does not support resume for LoRA. Then we leave the +following efforts to ``trainer`` and have a cup of coffee! + +Next Step +--------- + +Now, you are able to use a very simple script to perform different types +of SFT. Alternatively, you can use more advanced training libraries, +such as +`Axolotl `__ or +`LLaMA-Factory `__, to enjoy +more functionalities. To take a step forward, after SFT, you can +consider RLHF to align your model to human preferences! Stay tuned for +our next tutorial on RLHF! diff --git a/docs/source/training/SFT/index.rst b/docs/source/training/SFT/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..fc00e59d592e1677a6771cb3f4762c7871117599 --- /dev/null +++ b/docs/source/training/SFT/index.rst @@ -0,0 +1,8 @@ +SFT +================================= + +.. toctree:: + :maxdepth: 1 + + example + llama_factory diff --git a/docs/source/training/SFT/llama_factory.rst b/docs/source/training/SFT/llama_factory.rst new file mode 100644 index 0000000000000000000000000000000000000000..c6554f5cae4c8e4147a339eb69898e7f657b006c --- /dev/null +++ b/docs/source/training/SFT/llama_factory.rst @@ -0,0 +1,194 @@ +LLaMA-Factory +=================================== + +Here we provide a script for supervised finetuning Qwen1.5 with +`LLaMA-Factory `__. This +script for supervised finetuning (SFT) has the following features: + +- Support single-GPU and multi-GPU training; + +- Support full-parameter tuning, LoRA, Q-LoRA, Dora. + +In the following, we introduce more details about the usage of the +script. + +Installation +------------ + +Before you start, make sure you have installed the following packages: + +1. Follow the instructions of + `LLaMA-Factory `__, and build + the environment. +2. Install these packages (Optional): + +:: + + pip install deepspeed + pip install flash-attn --no-build-isolation + +3. If you want to use + `FlashAttention-2 `__, + make sure your CUDA is 11.6 and above. + +Data Preparation +---------------- + +LLaMA-Factory provides several training datasets in ``data`` folder, you +can use it directly. If you are using a custom dataset, please prepare +your dataset as follow. + +1. Organize your data in a **json** file and put your data in ``data`` + folder. LLaMA-Factory supports dataset in ``alpaca`` or ``sharegpt`` + format. + +- The dataset in ``alpaca`` format should follow the below format: + +.. code:: json + + [ + { + "instruction": "user instruction (required)", + "input": "user input (optional)", + "output": "model response (required)", + "system": "system prompt (optional)", + "history": [ + ["user instruction in the first round (optional)", "model response in the first round (optional)"], + ["user instruction in the second round (optional)", "model response in the second round (optional)"] + ] + } + ] + +- The dataset in ``sharegpt`` format should follow the below format: + +.. code:: json + + [ + { + "conversations": [ + { + "from": "human", + "value": "user instruction" + }, + { + "from": "gpt", + "value": "model response" + } + ], + "system": "system prompt (optional)", + "tools": "tool description (optional)" + } + ] + +2. Provide your dataset definition in ``data/dataset_info.json`` in the + following format . + +- For ``alpaca`` format dataset, the columns in ``dataset_info.json`` + should be: + +.. code:: json + + "dataset_name": { + "file_name": "dataset_name.json", + "columns": { + "prompt": "instruction", + "query": "input", + "response": "output", + "system": "system", + "history": "history" + } + } + +- For ``sharegpt`` format dataset, the columns in ``dataset_info.json`` + should be: + +.. code:: json + + "dataset_name": { + "file_name": "dataset_name.json", + "formatting": "sharegpt", + "columns": { + "messages": "conversations", + "system": "system", + "tools": "tools" + }, + "tags": { + "role_tag": "from", + "content_tag": "value", + "user_tag": "user", + "assistant_tag": "assistant" + } + } + +Training +-------- + +Execute the following training command: + +.. code:: bash + + DISTRIBUTED_ARGS=" + --nproc_per_node $NPROC_PER_NODE \ + --nnodes $NNODES \ + --node_rank $NODE_RANK \ + --master_addr $MASTER_ADDR \ + --master_port $MASTER_PORT + " + + torchrun $DISTRIBUTED_ARGS src/train_bash.py \ + --deepspeed $DS_CONFIG_PATH \ + --stage sft \ + --do_train \ + --use_fast_tokenizer \ + --flash_attn \ + --model_name_or_path $MODEL_PATH \ + --dataset your_dataset \ + --template qwen \ + --finetuning_type lora \ + --lora_target q_proj,v_proj\ + --output_dir $OUTPUT_PATH \ + --overwrite_cache \ + --overwrite_output_dir \ + --warmup_steps 100 \ + --weight_decay 0.1 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 4 \ + --ddp_timeout 9000 \ + --learning_rate 5e-6 \ + --lr_scheduler_type cosine \ + --logging_steps 1 \ + --cutoff_len 4096 \ + --save_steps 1000 \ + --plot_loss \ + --num_train_epochs 3 \ + --bf16 + +and enjoy the training process. To make changes to your training, you +can modify the arguments in the training command to adjust the +hyperparameters. One argument to note is ``cutoff_len``, which is the +maximum length of the training data. Control this parameter to avoid OOM +error. + +Merge LoRA +---------- + +If you train your model with LoRA, you probably need to merge adapter +parameters to the main branch. Run the following command to perform the +merging of LoRA adapters. + +.. code:: bash + + CUDA_VISIBLE_DEVICES=0 python src/export_model.py \ + --model_name_or_path path_to_base_model \ + --adapter_name_or_path path_to_adapter \ + --template default \ + --finetuning_type lora \ + --export_dir path_to_export \ + --export_size 2 \ + --export_legacy_format False + +Conclusion +---------- + +The above content is the simplest way to use LLaMA-Factory to train +Qwen. Feel free to dive into the details by checking the official repo! diff --git a/docs/source/web_ui/text_generation_webui.rst b/docs/source/web_ui/text_generation_webui.rst new file mode 100644 index 0000000000000000000000000000000000000000..93a325b5cf50c189593d6243daa035c4d513723d --- /dev/null +++ b/docs/source/web_ui/text_generation_webui.rst @@ -0,0 +1,96 @@ +Text Generation Web UI +======================================== + +`Text Generation Web +UI `__ (TGW, or +usually referred to “oobabooga”) is a popular web UI for text +generation, similar to +`AUTOMATIC1111/stable-diffusion-webui `__. +It has multiple interfaces, and supports multiple model backends, +including +`Transformers `__, +`llama.cpp `__ (through +`llama-cpp-python `__), +`ExLlamaV2 `__, +`AutoGPTQ `__, +`AutoAWQ `__, +`GPTQ-for-LLaMa `__, +`CTransformers `__, +`QuIP# `__. In this +section, we introduce how to run Qwen locally with TGW. + +Quickstart +---------- + +The simplest way to run TGW is to use the provided shell scripts in the +`repo `__. For the +first step, clone the repo and enter the directory: + +.. code:: bash + + git clone https://github.com/oobabooga/text-generation-webui + cd text-generation-webui + +You can directly run the ``start_linux.sh``, ``start_windows.bat``, +``start_macos.sh``, or ``start_wsl.bat`` script depending on your OS. +Alternatively you can manually install the requirements in your conda +environment. Here I take the practice on MacOS as an example. + +.. code:: bash + + conda create -n textgen python=3.11 + conda activate textgen + pip install torch torchvision torchaudio + +Then you can install the requirements by running ``pip install -r`` +based on your OS, e.g., + +.. code:: bash + + pip install -r requirements_apple_silicon.txt + +For ``bitsandbytes`` and ``llama-cpp-python`` inside the requirements, I +advise you to install them through ``pip`` directly. However, temporarily +please do not use GGUF as the performance with TGW is unsatisfactory. After +finishing the installation of required packages, you need to prepare your +models by putting the model files or directories in the folder ``./models``. +For example, you should put the transformers model directory of +``Qwen1.5-7B-Chat`` in the way shown below: + +:: + + text-generation-webui + ├── models + │   ├── Qwen1.5-7B-Chat + │   │   ├── config.json + │   │   ├── generation_config.json + │   │   ├── model-00001-of-00004.safetensor + │   │   ├── model-00002-of-00004.safetensor + │   │   ├── model-00003-of-00004.safetensor + │   │   ├── model-00004-of-00004.safetensor + │   │   ├── model.safetensor.index.json + │   │   ├── merges.txt + │   │   ├── tokenizer_config.json + │   │   └── vocab.json + +Then you just need to run + +.. code:: bash + + python server.py + +to launch your web UI service. Please browse to + +:: + + `http://localhost:7860/?__theme=dark` + +and enjoy playing with Qwen in a web UI! + +Next Step +--------- + +There are a lot more usages in TGW, where you can even enjoy role play, +use different types of quantized models, train LoRA, incorporate +extensions like stable diffusion and whisper, etc. Go to figure out more +advanced usages and apply them to Qwen models! diff --git a/examples/demo/cli_demo.py b/examples/demo/cli_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f85d926898618e67e91fe7408cab56a31efa40 --- /dev/null +++ b/examples/demo/cli_demo.py @@ -0,0 +1,265 @@ +# Copyright (c) Alibaba Cloud. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +"""A simple command-line interactive chat demo.""" + +import argparse +import os +import platform +import shutil +from copy import deepcopy +from threading import Thread + +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer +from transformers.trainer_utils import set_seed + +DEFAULT_CKPT_PATH = 'Qwen/Qwen1.5-7B-Chat' + +_WELCOME_MSG = '''\ +Welcome to use Qwen1.5-Chat model, type text to start chat, type :h to show command help. +(欢迎使用 Qwen1.5-Chat 模型,输入内容即可进行对话,:h 显示命令帮助。) + +Note: This demo is governed by the original license of Qwen1.5. +We strongly advise users not to knowingly generate or allow others to knowingly generate harmful content, including hate speech, violence, pornography, deception, etc. +(注:本演示受Qwen1.5的许可协议限制。我们强烈建议,用户不应传播及不应允许他人传播以下内容,包括但不限于仇恨言论、暴力、色情、欺诈相关的有害信息。) +''' +_HELP_MSG = '''\ +Commands: + :help / :h Show this help message 显示帮助信息 + :exit / :quit / :q Exit the demo 退出Demo + :clear / :cl Clear screen 清屏 + :clear-history / :clh Clear history 清除对话历史 + :history / :his Show history 显示对话历史 + :seed Show current random seed 显示当前随机种子 + :seed Set random seed to 设置随机种子 + :conf Show current generation config 显示生成配置 + :conf = Change generation config 修改生成配置 + :reset-conf Reset generation config 重置生成配置 +''' +_ALL_COMMAND_NAMES = [ + 'help', 'h', 'exit', 'quit', 'q', 'clear', 'cl', 'clear-history', 'clh', 'history', 'his', + 'seed', 'conf', 'reset-conf', +] + + +def _setup_readline(): + try: + import readline + except ImportError: + return + + _matches = [] + + def _completer(text, state): + nonlocal _matches + + if state == 0: + _matches = [cmd_name for cmd_name in _ALL_COMMAND_NAMES if cmd_name.startswith(text)] + if 0 <= state < len(_matches): + return _matches[state] + return None + + readline.set_completer(_completer) + readline.parse_and_bind('tab: complete') + + +def _load_model_tokenizer(args): + tokenizer = AutoTokenizer.from_pretrained( + args.checkpoint_path, resume_download=True, + ) + + if args.cpu_only: + device_map = "cpu" + else: + device_map = "auto" + + model = AutoModelForCausalLM.from_pretrained( + args.checkpoint_path, + device_map=device_map, + resume_download=True, + ).eval() + model.generation_config.max_new_tokens = 2048 # For chat. + + return model, tokenizer + + +def _gc(): + import gc + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + +def _clear_screen(): + if platform.system() == "Windows": + os.system("cls") + else: + os.system("clear") + + +def _print_history(history): + terminal_width = shutil.get_terminal_size()[0] + print(f'History ({len(history)})'.center(terminal_width, '=')) + for index, (query, response) in enumerate(history): + print(f'User[{index}]: {query}') + print(f'QWen[{index}]: {response}') + print('=' * terminal_width) + + +def _get_input() -> str: + while True: + try: + message = input('User> ').strip() + except UnicodeDecodeError: + print('[ERROR] Encoding error in input') + continue + except KeyboardInterrupt: + exit(1) + if message: + return message + print('[ERROR] Query is empty') + + +def _chat_stream(model, tokenizer, query, history): + conversation = [ + {'role': 'system', 'content': 'You are a helpful assistant.'}, + ] + for query_h, response_h in history: + conversation.append({'role': 'user', 'content': query_h}) + conversation.append({'role': 'assistant', 'content': response_h}) + conversation.append({'role': 'user', 'content': query}) + inputs = tokenizer.apply_chat_template( + conversation, + add_generation_prompt=True, + return_tensors='pt', + ) + inputs = inputs.to(model.device) + streamer = TextIteratorStreamer(tokenizer=tokenizer, skip_prompt=True, timeout=60.0, skip_special_tokens=True) + generation_kwargs = dict( + input_ids=inputs, + streamer=streamer, + ) + thread = Thread(target=model.generate, kwargs=generation_kwargs) + thread.start() + + for new_text in streamer: + yield new_text + + +def main(): + parser = argparse.ArgumentParser( + description='QWen1.5-Chat command-line interactive chat demo.') + parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH, + help="Checkpoint name or path, default to %(default)r") + parser.add_argument("-s", "--seed", type=int, default=1234, help="Random seed") + parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only") + args = parser.parse_args() + + history, response = [], '' + + model, tokenizer = _load_model_tokenizer(args) + orig_gen_config = deepcopy(model.generation_config) + + _setup_readline() + + _clear_screen() + print(_WELCOME_MSG) + + seed = args.seed + + while True: + query = _get_input() + + # Process commands. + if query.startswith(':'): + command_words = query[1:].strip().split() + if not command_words: + command = '' + else: + command = command_words[0] + + if command in ['exit', 'quit', 'q']: + break + elif command in ['clear', 'cl']: + _clear_screen() + print(_WELCOME_MSG) + _gc() + continue + elif command in ['clear-history', 'clh']: + print(f'[INFO] All {len(history)} history cleared') + history.clear() + _gc() + continue + elif command in ['help', 'h']: + print(_HELP_MSG) + continue + elif command in ['history', 'his']: + _print_history(history) + continue + elif command in ['seed']: + if len(command_words) == 1: + print(f'[INFO] Current random seed: {seed}') + continue + else: + new_seed_s = command_words[1] + try: + new_seed = int(new_seed_s) + except ValueError: + print(f'[WARNING] Fail to change random seed: {new_seed_s!r} is not a valid number') + else: + print(f'[INFO] Random seed changed to {new_seed}') + seed = new_seed + continue + elif command in ['conf']: + if len(command_words) == 1: + print(model.generation_config) + else: + for key_value_pairs_str in command_words[1:]: + eq_idx = key_value_pairs_str.find('=') + if eq_idx == -1: + print('[WARNING] format: =') + continue + conf_key, conf_value_str = key_value_pairs_str[:eq_idx], key_value_pairs_str[eq_idx + 1:] + try: + conf_value = eval(conf_value_str) + except Exception as e: + print(e) + continue + else: + print(f'[INFO] Change config: model.generation_config.{conf_key} = {conf_value}') + setattr(model.generation_config, conf_key, conf_value) + continue + elif command in ['reset-conf']: + print('[INFO] Reset generation config') + model.generation_config = deepcopy(orig_gen_config) + print(model.generation_config) + continue + else: + # As normal query. + pass + + # Run chat. + set_seed(seed) + _clear_screen() + print(f"\nUser: {query}") + print(f"\nQwen1.5-Chat: ", end="") + try: + partial_text = '' + for new_text in _chat_stream(model, tokenizer, query, history): + print(new_text, end='', flush=True) + partial_text += new_text + response = partial_text + print() + + except KeyboardInterrupt: + print('[WARNING] Generation interrupted') + continue + + history.append((query, response)) + + +if __name__ == "__main__": + main() diff --git a/examples/demo/web_demo.py b/examples/demo/web_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..681dc9e4d519f391c7451e703e4dffce44cd251e --- /dev/null +++ b/examples/demo/web_demo.py @@ -0,0 +1,230 @@ +# Copyright (c) Alibaba Cloud. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +"""A simple web interactive chat demo based on gradio.""" + +from argparse import ArgumentParser +from threading import Thread + +import gradio as gr +import mdtex2html +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer + +DEFAULT_CKPT_PATH = 'Qwen/Qwen1.5-7B-Chat' + + +def _get_args(): + parser = ArgumentParser() + parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH, + help="Checkpoint name or path, default to %(default)r") + parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only") + + parser.add_argument("--share", action="store_true", default=False, + help="Create a publicly shareable link for the interface.") + parser.add_argument("--inbrowser", action="store_true", default=False, + help="Automatically launch the interface in a new tab on the default browser.") + parser.add_argument("--server-port", type=int, default=8000, + help="Demo server port.") + parser.add_argument("--server-name", type=str, default="127.0.0.1", + help="Demo server name.") + + args = parser.parse_args() + return args + + +def _load_model_tokenizer(args): + tokenizer = AutoTokenizer.from_pretrained( + args.checkpoint_path, resume_download=True, + ) + + if args.cpu_only: + device_map = "cpu" + else: + device_map = "auto" + + model = AutoModelForCausalLM.from_pretrained( + args.checkpoint_path, + device_map=device_map, + resume_download=True, + ).eval() + model.generation_config.max_new_tokens = 2048 # For chat. + + return model, tokenizer + + +def _chat_stream(model, tokenizer, query, history): + conversation = [ + {'role': 'system', 'content': 'You are a helpful assistant.'}, + ] + for query_h, response_h in history: + conversation.append({'role': 'user', 'content': query_h}) + conversation.append({'role': 'assistant', 'content': response_h}) + conversation.append({'role': 'user', 'content': query}) + inputs = tokenizer.apply_chat_template( + conversation, + add_generation_prompt=True, + return_tensors='pt', + ) + inputs = inputs.to(model.device) + streamer = TextIteratorStreamer(tokenizer=tokenizer, skip_prompt=True, timeout=60.0, skip_special_tokens=True) + generation_kwargs = dict( + input_ids=inputs, + streamer=streamer, + ) + thread = Thread(target=model.generate, kwargs=generation_kwargs) + thread.start() + + for new_text in streamer: + yield new_text + + +def postprocess(self, y): + if y is None: + return [] + for i, (message, response) in enumerate(y): + y[i] = ( + None if message is None else mdtex2html.convert(message), + None if response is None else mdtex2html.convert(response), + ) + return y + + +gr.Chatbot.postprocess = postprocess + + +def _parse_text(text): + lines = text.split("\n") + lines = [line for line in lines if line != ""] + count = 0 + for i, line in enumerate(lines): + if "```" in line: + count += 1 + items = line.split("`") + if count % 2 == 1: + lines[i] = f'
'
+            else:
+                lines[i] = f"
" + else: + if i > 0: + if count % 2 == 1: + line = line.replace("`", r"\`") + line = line.replace("<", "<") + line = line.replace(">", ">") + line = line.replace(" ", " ") + line = line.replace("*", "*") + line = line.replace("_", "_") + line = line.replace("-", "-") + line = line.replace(".", ".") + line = line.replace("!", "!") + line = line.replace("(", "(") + line = line.replace(")", ")") + line = line.replace("$", "$") + lines[i] = "
" + line + text = "".join(lines) + return text + + +def _gc(): + import gc + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + +def _launch_demo(args, model, tokenizer): + + def predict(_query, _chatbot, _task_history): + print(f"User: {_parse_text(_query)}") + _chatbot.append((_parse_text(_query), "")) + full_response = "" + response = "" + for new_text in _chat_stream(model, tokenizer, _query, history=_task_history): + response += new_text + _chatbot[-1] = (_parse_text(_query), _parse_text(response)) + + yield _chatbot + full_response = _parse_text(response) + + print(f"History: {_task_history}") + _task_history.append((_query, full_response)) + print(f"Qwen1.5-Chat: {_parse_text(full_response)}") + + def regenerate(_chatbot, _task_history): + if not _task_history: + yield _chatbot + return + item = _task_history.pop(-1) + _chatbot.pop(-1) + yield from predict(item[0], _chatbot, _task_history) + + def reset_user_input(): + return gr.update(value="") + + def reset_state(_chatbot, _task_history): + _task_history.clear() + _chatbot.clear() + _gc() + return _chatbot + + with gr.Blocks() as demo: + gr.Markdown("""\ +

""") + gr.Markdown("""

Qwen1.5-Chat Bot
""") + gr.Markdown( + """\ +
This WebUI is based on Qwen1.5-Chat, developed by Alibaba Cloud. \ +(本WebUI基于Qwen1.5-Chat打造,实现聊天机器人功能。)
""") + gr.Markdown("""\ +
+Qwen1.5-7B 🤖 | +🤗  | +Qwen1.5-7B-Chat 🤖 | +🤗  | +Qwen1.5-14B 🤖 | +🤗  | +Qwen1.5-14B-Chat 🤖 | +🤗  | + Github
""") + + chatbot = gr.Chatbot(label='Qwen1.5-Chat', elem_classes="control-height") + query = gr.Textbox(lines=2, label='Input') + task_history = gr.State([]) + + with gr.Row(): + empty_btn = gr.Button("🧹 Clear History (清除历史)") + submit_btn = gr.Button("🚀 Submit (发送)") + regen_btn = gr.Button("🤔️ Regenerate (重试)") + + submit_btn.click(predict, [query, chatbot, task_history], [chatbot], show_progress=True) + submit_btn.click(reset_user_input, [], [query]) + empty_btn.click(reset_state, [chatbot, task_history], outputs=[chatbot], show_progress=True) + regen_btn.click(regenerate, [chatbot, task_history], [chatbot], show_progress=True) + + gr.Markdown("""\ +Note: This demo is governed by the original license of Qwen1.5. \ +We strongly advise users not to knowingly generate or allow others to knowingly generate harmful content, \ +including hate speech, violence, pornography, deception, etc. \ +(注:本演示受Qwen1.5的许可协议限制。我们强烈建议,用户不应传播及不应允许他人传播以下内容,\ +包括但不限于仇恨言论、暴力、色情、欺诈相关的有害信息。)""") + + demo.queue().launch( + share=args.share, + inbrowser=args.inbrowser, + server_port=args.server_port, + server_name=args.server_name, + ) + + +def main(): + args = _get_args() + + model, tokenizer = _load_model_tokenizer(args) + + _launch_demo(args, model, tokenizer) + + +if __name__ == '__main__': + main() diff --git a/examples/sft/ds_config_zero2.json b/examples/sft/ds_config_zero2.json new file mode 100644 index 0000000000000000000000000000000000000000..4be2c0b59190c4747033ea95b8a9716c7caee5ba --- /dev/null +++ b/examples/sft/ds_config_zero2.json @@ -0,0 +1,52 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + + "zero_optimization": { + "stage": 2, + "offload_optimizer": { + "device": "none", + "pin_memory": true + }, + "allgather_partitions": true, + "allgather_bucket_size": 2e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": 2e8, + "contiguous_gradients": true + }, + + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "steps_per_print": 100, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/examples/sft/ds_config_zero3.json b/examples/sft/ds_config_zero3.json new file mode 100644 index 0000000000000000000000000000000000000000..e30fe94e805835f26e3abc9f6a6a9751351eb052 --- /dev/null +++ b/examples/sft/ds_config_zero3.json @@ -0,0 +1,59 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "none", + "pin_memory": true + }, + "offload_param": { + "device": "none", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + }, + + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "steps_per_print": 100, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} diff --git a/examples/sft/finetune.py b/examples/sft/finetune.py new file mode 100644 index 0000000000000000000000000000000000000000..18094f391811a75da93c556d19f4eb3b1766b420 --- /dev/null +++ b/examples/sft/finetune.py @@ -0,0 +1,375 @@ +# This code is based on the revised code from fastchat based on tatsu-lab/stanford_alpaca. + + +from dataclasses import dataclass, field +import json +import logging +import os +import pathlib +from typing import Dict, Optional, List +import torch +from torch.utils.data import Dataset +from deepspeed import zero +from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint +from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer +from transformers import Trainer, BitsAndBytesConfig, deepspeed +from transformers.trainer_pt_utils import LabelSmoother +from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training +from accelerate.utils import DistributedType + + +IGNORE_TOKEN_ID = LabelSmoother.ignore_index + +local_rank = None + + +def rank0_print(*args): + if local_rank == 0: + print(*args) + + +@dataclass +class ModelArguments: + model_name_or_path: Optional[str] = field(default="Qwen/Qwen-7B") + + +@dataclass +class DataArguments: + data_path: str = field( + default=None, metadata={"help": "Path to the training data."} + ) + eval_data_path: str = field( + default=None, metadata={"help": "Path to the evaluation data."} + ) + lazy_preprocess: bool = False + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + model_max_length: int = field( + default=8192, + metadata={ + "help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)." + }, + ) + use_lora: bool = False + + +@dataclass +class LoraArguments: + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_target_modules: List[str] = field( + default_factory=lambda: [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "up_proj", + "gate_proj", + "down_proj", + ] + ) + lora_weight_path: str = "" + lora_bias: str = "none" + q_lora: bool = False + + +def maybe_zero_3(param): + if hasattr(param, "ds_id"): + assert param.ds_status == ZeroParamStatus.NOT_AVAILABLE + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v) for k, v in to_return.items()} + return to_return + + +def safe_save_model_for_hf_trainer( + trainer: transformers.Trainer, output_dir: str, bias="none" +): + """Collects the state dict and dump to disk.""" + # check if zero3 mode enabled + if deepspeed.is_deepspeed_zero3_enabled(): + state_dict = trainer.model_wrapped._zero3_consolidated_16bit_state_dict() + else: + if trainer.args.use_lora: + state_dict = get_peft_state_maybe_zero_3( + trainer.model.named_parameters(), bias + ) + else: + state_dict = trainer.model.state_dict() + if trainer.args.should_save and trainer.args.local_rank == 0: + trainer._save(output_dir, state_dict=state_dict) + + +def preprocess( + messages, + tokenizer: transformers.PreTrainedTokenizer, + max_len: int, +) -> Dict: + """Preprocesses the data for supervised fine-tuning.""" + + texts = [] + for i, msg in enumerate(messages): + texts.append( + tokenizer.apply_chat_template( + msg, + tokenize=True, + add_generation_prompt=False, + padding=True, + max_length=max_len, + truncation=True, + ) + ) + input_ids = torch.tensor(texts, dtype=torch.int) + target_ids = input_ids.clone() + target_ids[target_ids == tokenizer.pad_token_id] = IGNORE_TOKEN_ID + attention_mask = input_ids.ne(tokenizer.pad_token_id) + + return dict( + input_ids=input_ids, target_ids=target_ids, attention_mask=attention_mask + ) + + +class SupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" + + def __init__( + self, raw_data, tokenizer: transformers.PreTrainedTokenizer, max_len: int + ): + super(SupervisedDataset, self).__init__() + + rank0_print("Formatting inputs...") + messages = [example["messages"] for example in raw_data] + data_dict = preprocess(messages, tokenizer, max_len) + + self.input_ids = data_dict["input_ids"] + self.target_ids = data_dict["target_ids"] + self.attention_mask = data_dict["attention_mask"] + + def __len__(self): + return len(self.input_ids) + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + return dict( + input_ids=self.input_ids[i], + labels=self.target_ids[i], + attention_mask=self.attention_mask[i], + ) + + +class LazySupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" + + def __init__( + self, raw_data, tokenizer: transformers.PreTrainedTokenizer, max_len: int + ): + super(LazySupervisedDataset, self).__init__() + self.tokenizer = tokenizer + self.max_len = max_len + + rank0_print("Formatting inputs...Skip in lazy mode") + self.tokenizer = tokenizer + self.raw_data = raw_data + self.cached_data_dict = {} + + def __len__(self): + return len(self.raw_data) + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + if i in self.cached_data_dict: + return self.cached_data_dict[i] + + ret = preprocess([self.raw_data[i]["messages"]], self.tokenizer, self.max_len) + ret = dict( + input_ids=ret["input_ids"][0], + labels=ret["target_ids"][0], + attention_mask=ret["attention_mask"][0], + ) + self.cached_data_dict[i] = ret + + return ret + + +def make_supervised_data_module( + tokenizer: transformers.PreTrainedTokenizer, + data_args, + max_len, +) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + dataset_cls = ( + LazySupervisedDataset if data_args.lazy_preprocess else SupervisedDataset + ) + rank0_print("Loading data...") + + train_data = [] + with open(data_args.data_path, "r") as f: + for line in f: + train_data.append(json.loads(line)) + train_dataset = dataset_cls(train_data, tokenizer=tokenizer, max_len=max_len) + + if data_args.eval_data_path: + eval_data = [] + with open(data_args.eval_data_path, "r") as f: + for line in f: + eval_data.append(json.loads(line)) + eval_dataset = dataset_cls(eval_data, tokenizer=tokenizer, max_len=max_len) + else: + eval_dataset = None + + return dict(train_dataset=train_dataset, eval_dataset=eval_dataset) + + +def train(): + global local_rank + + parser = transformers.HfArgumentParser( + (ModelArguments, DataArguments, TrainingArguments, LoraArguments) + ) + ( + model_args, + data_args, + training_args, + lora_args, + ) = parser.parse_args_into_dataclasses() + + # This serves for single-gpu qlora. + if ( + getattr(training_args, "deepspeed", None) + and int(os.environ.get("WORLD_SIZE", 1)) == 1 + ): + training_args.distributed_state.distributed_type = DistributedType.DEEPSPEED + + local_rank = training_args.local_rank + + device_map = None + world_size = int(os.environ.get("WORLD_SIZE", 1)) + ddp = world_size != 1 + if lora_args.q_lora: + device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)} if ddp else "auto" + if len(training_args.fsdp) > 0 or deepspeed.is_deepspeed_zero3_enabled(): + logging.warning("FSDP or ZeRO3 is incompatible with QLoRA.") + + model_load_kwargs = { + "low_cpu_mem_usage": not deepspeed.is_deepspeed_zero3_enabled(), + } + + compute_dtype = ( + torch.float16 + if training_args.fp16 + else (torch.bfloat16 if training_args.bf16 else torch.float32) + ) + + # Load model and tokenizer + config = transformers.AutoConfig.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + ) + config.use_cache = False + + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, + config=config, + cache_dir=training_args.cache_dir, + device_map=device_map, + quantization_config=BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=compute_dtype, + ) + if training_args.use_lora and lora_args.q_lora + else None, + **model_load_kwargs, + ) + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right", + use_fast=False, + ) + + if training_args.use_lora: + lora_config = LoraConfig( + r=lora_args.lora_r, + lora_alpha=lora_args.lora_alpha, + target_modules=lora_args.lora_target_modules, + lora_dropout=lora_args.lora_dropout, + bias=lora_args.lora_bias, + task_type="CAUSAL_LM", + ) + if lora_args.q_lora: + model = prepare_model_for_kbit_training( + model, use_gradient_checkpointing=training_args.gradient_checkpointing + ) + + model = get_peft_model(model, lora_config) + + # Print peft trainable params + model.print_trainable_parameters() + + if training_args.gradient_checkpointing: + model.enable_input_require_grads() + + # Load data + data_module = make_supervised_data_module( + tokenizer=tokenizer, data_args=data_args, max_len=training_args.model_max_length + ) + + # Start trainer + trainer = Trainer( + model=model, tokenizer=tokenizer, args=training_args, **data_module + ) + + # `not training_args.use_lora` is a temporary workaround for the issue that there are problems with + # loading the checkpoint when using LoRA with DeepSpeed. + # Check this issue https://github.com/huggingface/peft/issues/746 for more information. + if ( + list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")) + and not training_args.use_lora + ): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + trainer.save_state() + + safe_save_model_for_hf_trainer( + trainer=trainer, output_dir=training_args.output_dir, bias=lora_args.lora_bias + ) + + +if __name__ == "__main__": + train() diff --git a/examples/sft/finetune.sh b/examples/sft/finetune.sh new file mode 100644 index 0000000000000000000000000000000000000000..71d7382af04d5cfa4db652c9ec20c87ef7834bfb --- /dev/null +++ b/examples/sft/finetune.sh @@ -0,0 +1,107 @@ +#!/bin/bash +export CUDA_DEVICE_MAX_CONNECTIONS=1 +DIR=`pwd` + +# Guide: +# This script supports distributed training on multi-gpu workers (as well as single-worker training). +# Please set the options below according to the comments. +# For multi-gpu workers training, these options should be manually set for each worker. +# After setting the options, please run the script on each worker. + +# Number of GPUs per GPU worker +GPUS_PER_NODE=$(python -c 'import torch; print(torch.cuda.device_count())') + +# Number of GPU workers, for single-worker training, please set to 1 +NNODES=${NNODES:-1} + +# The rank of this worker, should be in {0, ..., WORKER_CNT-1}, for single-worker training, please set to 0 +NODE_RANK=${NODE_RANK:-0} + +# The ip address of the rank-0 worker, for single-worker training, please set to localhost +MASTER_ADDR=${MASTER_ADDR:-localhost} + +# The port for communication +MASTER_PORT=${MASTER_PORT:-6001} + +MODEL="Qwen/Qwen1.5-7B" # Set the path if you do not want to load from huggingface directly +# ATTENTION: specify the path to your training data, which should be a json file consisting of a list of conversations. +# See the section for finetuning in README for more information. +DATA="path_to_data" +DS_CONFIG_PATH="finetune/ds_config_zero3.json" +USE_LORA=False +Q_LORA=False + +function usage() { + echo ' +Usage: bash finetune/finetune_lora_ds.sh [-m MODEL_PATH] [-d DATA_PATH] [--deepspeed DS_CONFIG_PATH] [--use_lora USE_LORA] [--q_lora Q_LORA] +' +} + +while [[ "$1" != "" ]]; do + case $1 in + -m | --model ) + shift + MODEL=$1 + ;; + -d | --data ) + shift + DATA=$1 + ;; + --deepspeed ) + shift + DS_CONFIG_PATH=$1 + ;; + --use_lora ) + shift + USE_LORA=$1 + ;; + --q_lora ) + shift + Q_LORA=$1 + ;; + -h | --help ) + usage + exit 0 + ;; + * ) + echo "Unknown argument ${1}" + exit 1 + ;; + esac + shift +done + +DISTRIBUTED_ARGS=" + --nproc_per_node $GPUS_PER_NODE \ + --nnodes $NNODES \ + --node_rank $NODE_RANK \ + --master_addr $MASTER_ADDR \ + --master_port $MASTER_PORT +" + +torchrun $DISTRIBUTED_ARGS finetune.py \ + --model_name_or_path $MODEL \ + --data_path $DATA \ + --bf16 True \ + --output_dir output_qwen \ + --num_train_epochs 5 \ + --per_device_train_batch_size 2 \ + --per_device_eval_batch_size 1 \ + --gradient_accumulation_steps 8 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 10 \ + --save_total_limit 10 \ + --learning_rate 3e-4 \ + --weight_decay 0.01 \ + --adam_beta2 0.95 \ + --warmup_ratio 0.01 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --report_to "none" \ + --model_max_length 512 \ + --lazy_preprocess True \ + --use_lora ${USE_LORA} \ + --q_lora ${Q_LORA} \ + --gradient_checkpointing \ + --deepspeed ${DS_CONFIG_PATH}