[
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "NOTICE",
    "content": "Copyright 2023-2024 01.AI\n\nThis work, [Your Model Name], is based on the work originally authored by 01.AI.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAttribution \n\nIf you create derivative works based on this model, please include the following attribution in your derivative works:\n\nThis work is a derivative of [The Yi-1.5 Series Model You Base On] by 01.AI, used under the Apache 2.0 License.\n\n\n\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n\n<picture> \n  <img src=\"https://raw.githubusercontent.com/01-ai/Yi/main/assets/img/Yi_logo_icon_light.svg\" width=\"150px\">\n</picture>\n\n</div>\n\n<br/>\n\n<p align=\"center\">\n  <a href=\"https://huggingface.co/01-ai\">🤗 HuggingFace</a> •\n  <a href=\"https://www.modelscope.cn/organization/01ai/\">🤖 ModelScope</a> •\n  <a href=\"https://wisemodel.cn/organization/01.AI\">🟣 wisemodel</a> \n  <br/>\n  <a href=\"https://discord.gg/hYUwWddeAu\">👾 Discord</a> •\n  <a href=\"https://twitter.com/01ai_yi\">🐤 Twitter</a> •\n  <a href=\"https://github.com/01-ai/Yi-1.5/issues/2\">💬 WeChat</a> \n  <br/>\n  <a href=\"https://arxiv.org/abs/2403.04652\">📝 Paper</a> •\n  <a href=\"https://01-ai.github.io/\">💪 Tech Blog</a> •\n  <a href=\"https://github.com/01-ai/Yi/tree/main?tab=readme-ov-file#faq\">🙌 FAQ</a> •\n  <a href=\"https://github.com/01-ai/Yi/tree/main?tab=readme-ov-file#learning-hub\">📗 Learning Hub</a>\n</p>\n\n---\n\n- [Intro](#intro)\n- [News](#news)\n- [Quick Start](#quick-start)\n- [Web Demo](#web-demo)\n- [Deployment](#deployment)\n- [Fine-tuning](#fine-tuning)\n- [API](#api)\n- [License](#license)\n\n## Intro\n\nYi-1.5 is an upgraded version of Yi. It is continuously pre-trained on Yi with a high-quality corpus of 500B tokens and fine-tuned on 3M diverse fine-tuning samples. \n\nCompared with Yi, Yi-1.5 delivers stronger performance in coding, math, reasoning, and instruction-following capability, while still maintaining excellent capabilities in language understanding, commonsense reasoning, and reading comprehension. \n\nYi-1.5 comes in 3 model sizes: 34B, 9B, and 6B. For model details and benchmarks, see [Model Card](https://huggingface.co/collections/01-ai/yi-15-2024-05-663f3ecab5f815a3eaca7ca8).\n\n## News\n\n- 2024-05-13: The Yi-1.5 series models are open-sourced, further improving coding, math, reasoning, and instruction-following abilities. \n\n## Requirements\n\n- Make sure Python 3.10 or a later version is installed.\n\n- Set up the environment and install the required packages.\n\n  ```bash\n  pip install -r requirements.txt\n  ```\n  \n- Download the Yi-1.5 model from [Hugging Face](https://huggingface.co/01-ai), [ModelScope](https://www.modelscope.cn/organization/01ai/), or [WiseModel](https://wisemodel.cn/organization/01.AI).\n\n## Quick Start\n\nThis tutorial runs Yi-1.5-34B-Chat locally on an A800 (80G).\n\n> **💡 Tip**: If you want to get started with the Yi model and explore different methods for inference, check out the [Yi Cookbook](https://github.com/01-ai/Yi/tree/main/Cookbook).\n\n  ```python\n  from transformers import AutoModelForCausalLM, AutoTokenizer\n  \n  model_path = '<your-model-path>'\n  \n  tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)\n  \n  # Since transformers 4.35.0, the GPT-Q/AWQ model can be loaded using AutoModelForCausalLM.\n  model = AutoModelForCausalLM.from_pretrained(\n      model_path,\n      device_map=\"auto\",\n      torch_dtype='auto'\n  ).eval()\n  \n  # Prompt content: \"hi\"\n  messages = [\n      {\"role\": \"user\", \"content\": \"hi\"}\n  ]\n  \n  input_ids = tokenizer.apply_chat_template(conversation=messages, tokenize=True, return_tensors='pt')\n  output_ids = model.generate(input_ids.to('cuda'), eos_token_id=tokenizer.eos_token_id)\n  response = tokenizer.decode(output_ids[0][input_ids.shape[1]:], skip_special_tokens=True)\n  \n  # Model response: \"Hello! How can I assist you today?\"\n  print(response)\n  ```\n\n### Ollama \n\n\n\n\nYou can run Yi-1.5 models on Ollama locally.\n\n1. After [installing Ollama](https://github.com/ollama/ollama/tree/main/docs), you can start the Ollama service. Note that keep this service running while you use Ollama.\n  \n    ```python\n    ollama serve\n    ```\n\n2. Run Yi-1.5 models. For more Yi models supported by Ollama, see [Yi tags](https://ollama.com/library/yi/tags).\n   \n    ```python\n    ollama run yi:v1.5\n    ```\n\n3. Chat with Yi-1.5 via OpenAI-compatible API. For more details on how to use Yi-1.5 via OpenAI API and REST API on Ollama, see [Ollama docs](https://github.com/ollama/ollama/tree/main/docs).\n\n    ```python\n    from openai import OpenAI\n    client = OpenAI(\n        base_url='http://localhost:11434/v1/',\n        api_key='ollama',  # required but ignored\n    )\n    chat_completion = client.chat.completions.create(\n        messages=[\n            {\n                'role': 'user',\n                'content': 'What is your name',\n            }\n        ],\n        model='yi:1.5',\n    )\n    ```\n\n## Deployment\n\nPrerequisites: Before deploying Yi-1.5 models, make sure you meet the [software and hardware requirements](https://github.com/01-ai/Yi/tree/main?tab=readme-ov-file#software-requirements). \n\n### vLLM\n\nPrerequisites: Download the latest version of [vLLM](https://docs.vllm.ai/en/latest/getting_started/installation.html).\n\n1. Start the server with a chat model.\n\n    ```bash\n    python -m vllm.entrypoints.openai.api_server  --model 01-ai/Yi-1.5-9B-Chat  --served-model-name Yi-1.5-9B-Chat\n    ```\n\n2. Use the chat API.\n\n  - HTTP\n\n    ```bash\n    curl http://localhost:8000/v1/chat/completions \\\n        -H \"Content-Type: application/json\" \\\n        -d '{\n            \"model\": \"Yi-1.5-9B-Chat\",\n            \"messages\": [\n                {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n                {\"role\": \"user\", \"content\": \"Who won the world series in 2020?\"}\n            ]\n        }'\n    ```\n\n  - Python client\n\n    ```python\n    from openai import OpenAI\n    # Set OpenAI's API key and API base to use vLLM's API server.\n    openai_api_key = \"EMPTY\"\n    openai_api_base = \"http://localhost:8000/v1\"\n    \n    client = OpenAI(\n        api_key=openai_api_key,\n        base_url=openai_api_base,\n    )\n    \n    chat_response = client.chat.completions.create(\n        model=\"Yi-1.5-9B-Chat\",\n        messages=[\n            {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n            {\"role\": \"user\", \"content\": \"Tell me a joke.\"},\n        ]\n    )\n    print(\"Chat response:\", chat_response)\n    ```\n\n## Web Demo\n\nYou can activate Yi-1.5-34B-Chat through the [huggingface chat ui](https://huggingface.co/chat/settings/01-ai/Yi-1.5-34B-Chat/) then experience it.\n\nOr you can build it locally by yourself, as follows:\n```\npython demo/web_demo.py -c <your-model-path>\n```\n\n## Fine-tuning\n\nYou can use [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory), [Swift](https://github.com/modelscope/swift), [XTuner](https://github.com/InternLM/xtuner), and [Firefly](https://github.com/yangjianxin1/Firefly) for fine-tuning. These frameworks all support fine-tuning the Yi series models.\n\n## API\n\nYi APIs are OpenAI-compatible and provided at [Yi Platform](https://platform.lingyiwanwu.com/). Sign up to get free tokens, and you can also pay-as-you-go at a competitive price. Additionally, Yi APIs are also deployed on [Replicate](https://replicate.com/search?query=01+ai) and [OpenRouter](https://openrouter.ai/models?q=01%20ai). \n\n## License\n\nThe code and weights of the Yi-1.5 series models are distributed under the [Apache 2.0 license](https://github.com/01-ai/Yi/blob/main/LICENSE).\n\nIf you create derivative works based on this model, please include the following attribution in your derivative works:\n\n    This work is a derivative of [The Yi-1.5 Series Model You Base On] by 01.AI, used under the Apache 2.0 License.\n\n<p align=\"right\"> [\n  <a href=\"#top\">Back to top ⬆️ </a>  ] \n</p>\n"
  },
  {
    "path": "demo/web_demo.py",
    "content": "import gradio as gr\nfrom argparse import ArgumentParser\nfrom threading import Thread\nfrom transformers import (\n    AutoModelForCausalLM,\n    AutoTokenizer,\n    TextIteratorStreamer,\n)\n\n\ndef respond(\n    message,\n    history: list[tuple[str, str]],\n    system_message,\n    max_tokens,\n    temperature,\n    top_p,\n):\n    messages = [{\"role\": \"system\", \"content\": system_message}]\n\n    for val in history:\n        if val[0]:\n            messages.append({\"role\": \"user\", \"content\": val[0]})\n        if val[1]:\n            messages.append({\"role\": \"assistant\", \"content\": val[1]})\n\n    messages.append({\"role\": \"user\", \"content\": message})\n\n    model_inputs = tokenizer.apply_chat_template(\n        messages, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\"\n    ).to(next(model.parameters()).device)\n\n    streamer = TextIteratorStreamer(\n        tokenizer, timeout=60, skip_prompt=True, skip_special_tokens=True\n    )\n    generate_kwargs = {\n        \"input_ids\": model_inputs,\n        \"streamer\": streamer,\n        \"max_new_tokens\": max_tokens,\n        \"do_sample\": True,\n        \"top_p\": top_p,\n        \"temperature\": temperature,\n        \"repetition_penalty\": 1.2,\n        \"eos_token_id\": [tokenizer.eos_token_id],\n    }\n    t = Thread(target=model.generate, kwargs=generate_kwargs)\n    t.start()\n    response = \"\"\n    for new_token in streamer:\n        if new_token != \"\":\n            response += new_token\n            yield response\n\n\n\"\"\"\nFor information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface\n\"\"\"\ndemo = gr.ChatInterface(\n    respond,\n    additional_inputs=[\n        gr.Textbox(value=\"You are a friendly Chatbot.\", label=\"System message\"),\n        gr.Slider(minimum=1, maximum=2048, value=512, step=1, label=\"Max new tokens\"),\n        gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label=\"Temperature\"),\n        gr.Slider(\n            minimum=0.1,\n            maximum=1.0,\n            value=0.95,\n            step=0.05,\n            label=\"Top-p (nucleus sampling)\",\n        ),\n    ],\n)\n\n\nif __name__ == \"__main__\":\n    parser = ArgumentParser()\n    parser.add_argument(\n        \"-c\",\n        \"--checkpoint-path\",\n        type=str,\n        default=\"01-ai/Yi-1.5-34B-Chat\",\n        help=\"Checkpoint name or path, default to %(default)r\",\n    )\n    parser.add_argument(\n        \"--share\",\n        action=\"store_true\",\n        default=False,\n        help=\"Create a publicly shareable link for the interface.\",\n    )\n    parser.add_argument(\n        \"--inbrowser\",\n        action=\"store_true\",\n        default=True,\n        help=\"Automatically launch the interface in a new tab on the default browser.\",\n    )\n    parser.add_argument(\n        \"--server-port\", type=int, default=8000, help=\"Demo server port.\"\n    )\n    parser.add_argument(\n        \"--server-name\", type=str, default=\"127.0.0.1\", help=\"Demo server name.\"\n    )\n\n    args = parser.parse_args()\n\n    tokenizer = AutoTokenizer.from_pretrained(args.checkpoint_path, use_fast=False)\n    model = AutoModelForCausalLM.from_pretrained(\n        args.checkpoint_path, device_map=\"auto\", torch_dtype=\"auto\"\n    ).eval()\n\n    demo.launch(\n        server_name=args.server_name,\n        server_port=args.server_port,\n        inbrowser=args.inbrowser,\n        share=args.share,\n    )\n"
  },
  {
    "path": "requirements.txt",
    "content": "transformers>=4.36.2\ngradio>=4.13.0\ntorch>=2.0.1,<=2.3.0\nsentencepiece\naccelerate"
  }
]