[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n"
  },
  {
    "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": "README.md",
    "content": "# LLaSM: Large Language and Speech Model\n\n[![](https://img.shields.io/badge/LLaSM-Chinese-blue)](https://huggingface.co/spaces/LinkSoul/LLaSM) [![](https://img.shields.io/badge/Commercial-Support-blue)](https://huggingface.co/spaces/LinkSoul/LLaSM) [![](https://img.shields.io/badge/License-Apache_v2-blue)](https://github.com/LinkSoul-AI/LLaSM/blob/main/LICENSE) [![](https://img.shields.io/badge/Paper-arXiv-red)](https://arxiv.org/abs/2308.15930) [![](https://img.shields.io/badge/HuggingFace-Live_Demo-green)](https://huggingface.co/spaces/LinkSoul/LLaSM) [![](https://img.shields.io/badge/Datasets-LLaSM_Audio_Instructions-yellow)](https://huggingface.co/datasets/LinkSoul/LLaSM-Audio-Instructions)\n\n开源，可商用的**中英文双语语音-语言助手 LLaSM 以及中英文语音 SFT 数据集 LLaSM-Audio-Instructions**，第一个支持中英文语音-文本多模态对话的开源可商用对话模型。\n\n<p align=\"center\">\n    <img src=\".github/preview.jpg\" width=\"40%\">\n</p>\n\n## 模型框架\n\n![Framework](.github/framework.png)\n\n## 基础演示\n\n![Base Demo](.github/demo.gif)\n\n## 在线试玩\n\n> Talk is cheap, Show you the Demo.\n- [Demo 地址 / Hugging Face Spaces](https://huggingface.co/spaces/LinkSoul/LLaSM) \n\n## 论文\n- arXiv 链接：https://arxiv.org/abs/2308.15930\n\n## 资源下载\n\n- Hugging Face模型下载：\n  - [LLaSM-Chinese-Llama-2-7B](https://huggingface.co/LinkSoul/LLaSM-Cllama2)\n  - [LLaSM-Baichuan-7B](https://huggingface.co/LinkSoul/LLaSM-Baichuan)\n\n- 百度网盘下载:\n  - [LLaSM-Chinese-Llama-2-7B](https://pan.baidu.com/s/1PaipNDfqV7f3W1-tl5rwzA?pwd=2549)\n  - [LLaSM-Baichuan-7B](https://pan.baidu.com/s/1QZrXA8IJXclN77T4jM7tEw?pwd=y2p7)\n\n- 语言模型:\n  - [Chinese-Llama-2-7b](https://github.com/LinkSoul-AI/Chinese-Llama-2-7b)\n  - [Baichuan-7B](https://huggingface.co/baichuan-inc/Baichuan-7B)\n\n- 数据集：[LLaSM-Audio-Instructions](https://huggingface.co/datasets/LinkSoul/LLaSM-Audio-Instructions)\n\n## 环境安装\n```shell\n# clone the repository\ngit clone https://github.com/LinkSoul-AI/LLaSM\ncd LLaSM\n\n# install package\nconda create -n llasm python=3.10 -y\nconda activate llasm\npip install --upgrade pip\npip install -e .\n```\n\n## 快速测试\n- 下载 Whisper large v2 模型：https://huggingface.co/openai/whisper-large-v2\n\n```shell\nexport LLASM_DEVICE=\"cuda:0\"\npython infer.py \\\n    --input_audio_file PATH/TO/YOUR/AUDIO \\\n    --llasm_model PATH/TO/LLaSM/MODEL \\\n    --llasm_audio_tower PATH/TO/WHISPER/MODEL \\\n    --llm_type \"Chinese_llama2\" or \"baichuan\" \\\n```\n\n## TODO\n- 如何训练\n- int4 量化\n- docker 部署\n\n## 相关项目\n- [Chinese-Llama-2-7B](https://huggingface.co/LinkSoul/Chinese-Llama-2-7b)\n- [Whisper](https://ai.meta.com/llama/)\n- [baichuan-inc/Baichuan-7B](https://huggingface.co/baichuan-inc/Baichuan-7B)\n\n\n## 项目协议\n\n[Apache-2.0 license](https://github.com/LinkSoul-AI/LLaSM/blob/main/LICENSE)\n\n## Citation\n\n如果您发现我们的工作和此仓库有用，欢迎给一个星星 :star: 鼓励我们一下 :beer::\n```bibtex\n@misc{shu2023llasm,\n      title={LLaSM: Large Language and Speech Model}, \n      author={Yu Shu and Siwei Dong and Guangyao Chen and Wenhao Huang and Ruihua Zhang and Daochen Shi and Qiqi Xiang and Yemin Shi},\n      year={2023},\n      eprint={2308.15930},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n```\n\n## 微信交流群\n\n<img src=\".github/QRcode.jpg\" alt=\"微信交流群\" width=\"300\"/>\n"
  },
  {
    "path": "examples/0.txt",
    "content": "请介绍一下勾股定理"
  },
  {
    "path": "examples/1.txt",
    "content": "世界上人口最多的是哪个国家\n"
  },
  {
    "path": "examples/2.txt",
    "content": "请介绍一下北京\n"
  },
  {
    "path": "infer.py",
    "content": "import os\nimport librosa\nimport argparse\n\nimport torch\n\nfrom transformers import AutoTokenizer\nfrom transformers import (\n    WhisperProcessor,\n    WhisperModel,\n)\n\nfrom llasm import LlaaaLlamaForCausalLM\nfrom infer_tokenize import tokenize\nfrom logger import print_signature\n\n\nDEFAULT_AUDIO_PATCH_TOKEN = \"<au_patch>\"\nDEFAULT_AUDIO_START_TOKEN = \"<au_start>\"\nDEFAULT_AUDIO_END_TOKEN = \"<au_end>\"\n\nclass Setting:\n    def __init__(self):\n        self.device = os.environ.get(\"LLASM_DEVICE\", \"cuda\")\n        self.llasm_context_len = 2048\n        self.sampling_rate = 16000\n        self.audio_token_len = 64\n        self.stop = \"</s>\"\n\nCONFIG = Setting()\n\n\ndef main(args):\n    input_audio_file = args.input_audio_file\n    temperature = args.temperature\n    max_new_tokens = args.max_new_tokens\n\n    # step0: load tokenizer\n    tokenizer = AutoTokenizer.from_pretrained(args.llasm_model)\n    # step0-1: add special token <au_patch>/<au_start>/<au_end>\n    tokenizer.add_tokens([DEFAULT_AUDIO_PATCH_TOKEN], special_tokens=True)\n    tokenizer.add_tokens([DEFAULT_AUDIO_START_TOKEN, DEFAULT_AUDIO_END_TOKEN], special_tokens=True)\n\n    # step1: load model\n    model = LlaaaLlamaForCausalLM.from_pretrained(\n        args.llasm_model,\n        torch_dtype=torch.float16,\n        low_cpu_mem_usage=True).to(CONFIG.device)\n\n    # step2: load audio processor\n    audio_processor = WhisperProcessor.from_pretrained(args.llasm_audio_tower, torch_dtype=torch.float16)\n\n    # step3: load audio tower\n    audio_tower = WhisperModel.from_pretrained(\n        args.llasm_audio_tower,\n        torch_dtype=torch.float16,\n        low_cpu_mem_usage=True).to(CONFIG.device)\n    # step3-1: update audio_tower config for setting special tokens\n    audio_config = audio_tower.config\n    audio_config.audio_patch_token = tokenizer.convert_tokens_to_ids([DEFAULT_AUDIO_PATCH_TOKEN])[0]\n    audio_config.audio_start_token, audio_config.audio_end_token = tokenizer.convert_tokens_to_ids([DEFAULT_AUDIO_START_TOKEN, DEFAULT_AUDIO_END_TOKEN])\n    model.get_model().audio_tower[0] = audio_tower\n\n    # step4 preprocessing input audio\n    audio, _ = librosa.load(input_audio_file, sr=CONFIG.sampling_rate)\n    audio_feat = audio_processor(audio, sampling_rate=CONFIG.sampling_rate, return_tensors=\"pt\").input_features\n    audio_feat = audio_feat.unsqueeze(0).unsqueeze(0).to(CONFIG.device, dtype=torch.float16)\n\n    # step5: tokenize\n    qs = DEFAULT_AUDIO_START_TOKEN + DEFAULT_AUDIO_PATCH_TOKEN * CONFIG.audio_token_len + DEFAULT_AUDIO_END_TOKEN\n    input_qs = {\n        \"conversations\": [{\n            \"from\": \"human\",\n            \"value\": qs,\n        },{\n            \"from\": \"gpt\",\n            \"value\": \"\"\n        }]\n    }\n    input_ids = torch.tensor([tokenize(input_qs, tokenizer, args.llm_type)]).to(CONFIG.device)\n\n    # step6: infer run\n    stop_str = CONFIG.stop\n    output_ids = model.generate(input_ids,audios=audio_feat,do_sample=True,temperature=temperature,max_new_tokens=max_new_tokens)\n\n    input_token_len = input_ids.shape[1]\n    n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()\n    if n_diff_input_output > 0:\n        print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')\n    outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]\n\n    outputs = outputs.strip()\n    if outputs.endswith(stop_str):\n        outputs = outputs[:-len(stop_str)]\n    outputs = outputs.strip()\n    \n    label = []\n    with open(input_audio_file[:-len('mp3')] + 'txt', 'r') as fh:\n        for ln in fh:\n            label.append(ln.strip())\n    text = ''.join(label)\n    \n    print_signature()\n    print (f\"Human: {input_audio_file} ({text})\")\n    print (f\"LLaSM: {outputs}\")\n    print (\"=\"*80)\n    print (\"Go to the Demo page, and have a try!\")\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--input_audio_file', type=str, default='./examples/0.mp3')\n    parser.add_argument('--llasm_model', type=str, default='path/to/llasm_model')\n    parser.add_argument('--llasm_audio_tower', type=str, default='path/to/whisper_large_v2')\n    parser.add_argument('--llm_type', type=str, default='Chinese_llama2')\n    parser.add_argument('--temperature', type=float, default=0.2)\n    parser.add_argument('--max_new_tokens', type=int, default=1024)\n    args = parser.parse_args()\n    main(args)"
  },
  {
    "path": "infer_tokenize.py",
    "content": "\n\nB_INST, E_INST = \"[INST]\", \"[/INST]\"\nB_SYS, E_SYS = \"<<SYS>>\\n\", \"\\n<</SYS>>\\n\\n\"\nsimple_audio_conv_multimodal = {\n    \"system\": \"You are a helpful language and speech assistant. You are able to understand the speech content that the user provides, and assist the user with a variety of tasks using natural language.\",\n    \"roles\": {\"human\": \"USER\", \"gpt\": \"ASSISTANT\"},\n}\n\ndef tokenize_baichuan(item, tokenizer):\n    roles = simple_audio_conv_multimodal[\"roles\"]\n    input_ids = []\n    if \"instruction\" in item and len(item[\"instruction\"]) > 0:\n        system = item[\"instruction\"]\n    else:\n        system = simple_audio_conv_multimodal[\"system\"]\n    system_ids = tokenizer.encode(system, add_special_tokens=False)\n    input_ids += system_ids\n    for i, turn in enumerate(item[\"conversations\"]):\n        role = roles.get(turn['from'], 'USER')\n        content = turn['value']\n        content = content.strip()\n        if role == 'ASSISTANT' and content != '':\n            content += '</s>'\n        role_ids = tokenizer.encode(role + \":\", add_special_tokens=False)\n        content_ids = tokenizer.encode(content, add_special_tokens=False, truncation=True,\n                                       max_length=tokenizer.model_max_length)\n        input_ids += role_ids + content_ids\n\n    if tokenizer.add_bos_token:\n        input_ids = [tokenizer.bos_token_id] + input_ids\n\n    input_ids = input_ids[-tokenizer.model_max_length:]\n\n    return input_ids\n\ndef tokenize_Cllama2(item, tokenizer):\n    input_ids = []\n    if \"instruction\" in item and len(item[\"instruction\"]) > 0:\n        system = item[\"instruction\"]\n    else:\n        system = simple_audio_conv_multimodal[\"system\"]\n    system = B_SYS + system + E_SYS\n    system_ids = tokenizer.encode(system, add_special_tokens=False)\n    input_ids += system_ids\n    item[\"conversations\"][0]['value'] = system + item[\"conversations\"][0]['value']\n    for i, turn in enumerate(item[\"conversations\"]):\n        role = turn['from']\n        content = turn['value']\n        content = content.strip()\n        if role == 'human':\n            content = f\"{B_INST} {content} {E_INST} \"\n            content_ids = tokenizer.encode(content)\n        else:\n            # assert role == \"gpt\"\n            if content == \"\":\n                content_ids = []\n            else:\n                content = f\"{content} \"\n                content_ids = tokenizer.encode(content, add_special_tokens=False) + [tokenizer.eos_token_id]   # add_special_tokens=False remove bos token, and add eos at the end\n        input_ids += content_ids\n\n    input_ids = input_ids[-tokenizer.model_max_length:]\n\n    return input_ids\n\n\ndef tokenize(item, tokenizer, llm_type):\n    if llm_type == \"Chinese_llama2\":\n        return tokenize_Cllama2(item, tokenizer)\n    elif llm_type == \"baichuan\":\n        return tokenize_baichuan(item, tokenizer)\n    else:\n        raise ValueError (f\"Invalid llm type {llm_type}, please choose in ['Chinese_llama2', 'baichuan']\")"
  },
  {
    "path": "llasm.py",
    "content": "from typing import List, Optional, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import CrossEntropyLoss\n\nfrom transformers import AutoConfig, AutoModelForCausalLM, \\\n                         LlamaConfig, LlamaModel, LlamaForCausalLM\n\nfrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast\nfrom transformers import (\n    WhisperProcessor,\n    WhisperModel,\n)\n\n\nDEFAULT_AUDIO_PATCH_TOKEN = \"<au_patch>\"\nDEFAULT_AUDIO_START_TOKEN = \"<au_start>\"\nDEFAULT_AUDIO_END_TOKEN = \"<au_end>\"\n\n\nclass LlaaaConfig(LlamaConfig):\n    model_type = \"llaaa\"\n\n\ndef load_whisper(audio_tower_name):\n    model = WhisperModel.from_pretrained(audio_tower_name)\n    model.config.forced_decoder_ids = None\n    return model\n\n\nclass LlaaaLlamaModel(LlamaModel):\n    config_class = LlaaaConfig\n\n    def __init__(self, config: LlamaConfig):\n        super(LlaaaLlamaModel, self).__init__(config)\n\n        if hasattr(config, \"mm_audio_tower\"):\n            # HACK: for FSDP\n            self.audio_tower = [load_whisper(config.mm_audio_tower)]\n\n        if hasattr(config, \"use_mm_proj\"):\n            self.mm_projector = nn.Linear(config.mm_hidden_size, config.hidden_size)\n\n    def initialize_audio_modules(self, audio_tower, audio_token_len, pretrain_mm_mlp_adapter=None):\n        self.config.mm_audio_tower = audio_tower\n\n        processor = WhisperProcessor.from_pretrained(audio_tower)\n\n        if not hasattr(self, 'audio_tower'):\n            audio_tower = load_whisper(audio_tower)\n        else:\n            audio_tower = self.audio_tower[0]\n        audio_tower.requires_grad_(False)\n        audio_tower = audio_tower.to(torch.float16)\n        self.audio_tower = [audio_tower]\n\n        self.config.use_mm_proj = True\n        self.config.mm_hidden_size = 1280\n        self.config.audio_token_len = audio_token_len\n\n        if not hasattr(self, 'mm_projector'):\n            self.mm_projector = nn.Linear(self.config.mm_hidden_size, self.config.hidden_size)\n\n        if pretrain_mm_mlp_adapter is not None:\n            mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')\n            self.mm_projector.load_state_dict({k.split('.')[-1]: v for k, v in mm_projector_weights.items()})\n\n        return dict(\n            processor=processor,\n        )\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        past_key_values: Optional[List[torch.FloatTensor]] = None,\n        inputs_embeds: Optional[torch.FloatTensor] = None,\n        use_cache: Optional[bool] = None,\n        output_attentions: Optional[bool] = None,\n        output_hidden_states: Optional[bool] = None,\n        audios: Optional[torch.FloatTensor] = None,\n        return_dict: Optional[bool] = None,\n    ) -> Union[Tuple, BaseModelOutputWithPast]:\n\n        # HACK: replace back original embeddings for LLaAA pretraining\n        orig_embeds_params = getattr(self, 'orig_embeds_params', None)\n\n        if inputs_embeds is None:\n            inputs_embeds = self.embed_tokens(input_ids)\n\n        audio_tower = getattr(self, 'audio_tower', None)\n        if audio_tower is not None and (input_ids.shape[1] != 1 or self.training) and audios is not None:\n            audio_tower = audio_tower[0]  # HACK: for FSDP\n            with torch.no_grad():\n                bs_audio_features = []\n                for audios_list in audios:\n                    if len(audios_list) == 0:\n                        dummy_audio_feature = torch.zeros(self.config.audio_token_len, self.config.mm_hidden_size, device=inputs_embeds.device, dtype=inputs_embeds.dtype)\n                        audio_features = [dummy_audio_feature]\n                    else:\n                        audio_features = []\n                        for audio in audios_list:\n                            decoder_input_ids = torch.ones((1, self.config.audio_token_len)) * audio_tower.config.decoder_start_token_id\n                            decoder_input_ids = decoder_input_ids.to(audio.device).to(torch.long)\n                            audio_feature = audio_tower(audio, decoder_input_ids=decoder_input_ids).last_hidden_state\n                            audio_features.append(audio_feature)\n                    bs_audio_features.append(audio_features)\n\n            audio_config = audio_tower.config\n            new_input_embeds = []\n            for cur_input_ids, cur_input_embeds, cur_audio_features in zip(input_ids, inputs_embeds, bs_audio_features):\n                if (cur_input_ids == audio_config.audio_patch_token).sum() == 0:\n                    # multimodal LLM, but the current sample is not multimodal, for using both language and audio data\n                    dummy_audio_features = self.mm_projector(cur_audio_features[0])\n                    cur_input_embeds = cur_input_embeds + (0. * dummy_audio_features).sum()\n                    new_input_embeds.append(cur_input_embeds)\n                    continue\n                if (cur_input_ids == audio_config.audio_start_token).sum() != (cur_input_ids == audio_config.audio_end_token).sum():\n                    raise ValueError(\"The number of audio start tokens and audio end tokens should be the same.\")\n                audio_start_tokens = torch.where(cur_input_ids == audio_config.audio_start_token)[0]\n                if len(audio_start_tokens) != len(cur_audio_features):\n                    raise ValueError(f\"The number of audio start tokens ({len(audio_start_tokens)}) and audio features ({len(cur_audio_features)}) should be the same.\")\n                for audio_start_token_pos, cur_audio_feature in zip(audio_start_tokens, cur_audio_features):\n                    cur_audio_feature = self.mm_projector(cur_audio_feature)[0]\n                    cur_audio_feature = cur_audio_feature.to(device=cur_input_embeds.device)\n                    num_patches = cur_audio_feature.shape[0]\n                    if cur_input_ids[audio_start_token_pos + num_patches + 1] != audio_config.audio_end_token:\n                        raise ValueError(\"The audio end token should follow the audio start token.\")\n                    if orig_embeds_params is not None:\n                        cur_new_input_embeds = torch.cat(\n                            (cur_input_embeds[:audio_start_token_pos].detach(),\n                             cur_input_embeds[audio_start_token_pos:audio_start_token_pos+1],\n                             cur_audio_feature,\n                             cur_input_embeds[audio_start_token_pos + num_patches + 1:audio_start_token_pos + num_patches + 2],\n                             cur_input_embeds[audio_start_token_pos + num_patches + 2:].detach()), dim=0)\n                    else:\n                        cur_new_input_embeds = torch.cat((\n                            cur_input_embeds[:audio_start_token_pos+1],\n                            cur_audio_feature,\n                            cur_input_embeds[audio_start_token_pos + num_patches + 1:]), dim=0)\n                new_input_embeds.append(cur_new_input_embeds)\n\n            inputs_embeds = torch.stack(new_input_embeds, dim=0)\n\n        return super(LlaaaLlamaModel, self).forward(\n            input_ids=None, attention_mask=attention_mask, past_key_values=past_key_values,\n            inputs_embeds=inputs_embeds, use_cache=use_cache,\n            output_attentions=output_attentions, output_hidden_states=output_hidden_states,\n            return_dict=return_dict\n        )\n\n\nclass LlaaaLlamaForCausalLM(LlamaForCausalLM):\n    config_class = LlaaaConfig\n\n    def __init__(self, config):\n        super(LlamaForCausalLM, self).__init__(config)\n        self.model = LlaaaLlamaModel(config)\n\n        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n        # Initialize weights and apply final processing\n        self.post_init()\n\n    def get_model(self):\n        return self.model\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        past_key_values: Optional[List[torch.FloatTensor]] = None,\n        inputs_embeds: Optional[torch.FloatTensor] = None,\n        labels: Optional[torch.LongTensor] = None,\n        use_cache: Optional[bool] = None,\n        output_attentions: Optional[bool] = None,\n        output_hidden_states: Optional[bool] = None,\n        audios: Optional[torch.FloatTensor] = None,\n        return_dict: Optional[bool] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n        output_hidden_states = (\n            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n        )\n        return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n        # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n        outputs = self.model(\n            input_ids=input_ids,\n            attention_mask=attention_mask,\n            past_key_values=past_key_values,\n            inputs_embeds=inputs_embeds,\n            use_cache=use_cache,\n            output_attentions=output_attentions,\n            output_hidden_states=output_hidden_states,\n            return_dict=return_dict,\n            audios=audios\n        )\n\n        hidden_states = outputs[0]\n        logits = self.lm_head(hidden_states)\n\n        loss = None\n        if labels is not None:\n            # Shift so that tokens < n predict n\n            shift_logits = logits[..., :-1, :].contiguous()\n            shift_labels = labels[..., 1:].contiguous()\n            # Flatten the tokens\n            loss_fct = CrossEntropyLoss()\n            shift_logits = shift_logits.view(-1, self.config.vocab_size)\n            shift_labels = shift_labels.view(-1)\n            # Enable model/pipeline parallelism\n            shift_labels = shift_labels.to(shift_logits.device)\n            loss = loss_fct(shift_logits, shift_labels)\n\n        if not return_dict:\n            output = (logits,) + outputs[1:]\n            return (loss,) + output if loss is not None else output\n\n        return CausalLMOutputWithPast(\n            loss=loss,\n            logits=logits,\n            past_key_values=outputs.past_key_values,\n            hidden_states=outputs.hidden_states,\n            attentions=outputs.attentions,\n        )\n\n    def prepare_inputs_for_generation(\n        self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n    ):\n        if past_key_values:\n            input_ids = input_ids[:, -1:]\n\n        # if `inputs_embeds` are passed, we only want to use them in the 1st generation step\n        if inputs_embeds is not None and past_key_values is None:\n            model_inputs = {\"inputs_embeds\": inputs_embeds}\n        else:\n            model_inputs = {\"input_ids\": input_ids}\n\n        model_inputs.update(\n            {\n                \"past_key_values\": past_key_values,\n                \"use_cache\": kwargs.get(\"use_cache\"),\n                \"attention_mask\": attention_mask,\n                \"audios\": kwargs.get(\"audios\", None),\n            }\n        )\n        return model_inputs\n\n    def initialize_audio_tokenizer(self, tokenizer, device,\n                                    tune_mm_mlp_adapter=False, pretrain_mm_mlp_adapter=None):\n        num_new_tokens = tokenizer.add_tokens([DEFAULT_AUDIO_PATCH_TOKEN], special_tokens=True)\n        self.resize_token_embeddings(len(tokenizer))\n\n        num_new_tokens += tokenizer.add_tokens([DEFAULT_AUDIO_START_TOKEN, DEFAULT_AUDIO_END_TOKEN], special_tokens=True)\n        self.resize_token_embeddings(len(tokenizer))\n\n        if num_new_tokens > 0:\n            input_embeddings = self.get_input_embeddings().weight.data\n            output_embeddings = self.get_output_embeddings().weight.data\n\n            input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(\n                dim=0, keepdim=True)\n            output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(\n                dim=0, keepdim=True)\n\n            input_embeddings[-num_new_tokens:] = input_embeddings_avg\n            output_embeddings[-num_new_tokens:] = output_embeddings_avg\n\n        if tune_mm_mlp_adapter:\n            self.get_model().orig_embeds_params = [self.get_input_embeddings().weight.data.clone().to(device=device)]\n            for p in self.get_input_embeddings().parameters():\n                p.requires_grad = True\n            for p in self.get_output_embeddings().parameters():\n                p.requires_grad = False\n\n        if pretrain_mm_mlp_adapter and num_new_tokens > 0:\n            mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')\n            embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']\n            assert num_new_tokens == 3\n            if input_embeddings.shape == embed_tokens_weight.shape:\n                input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]\n            elif embed_tokens_weight.shape[0] == num_new_tokens:\n                input_embeddings[-num_new_tokens:] = embed_tokens_weight\n            else:\n                raise ValueError(f\"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.\")\n\n        audio_patch_token = tokenizer.convert_tokens_to_ids([DEFAULT_AUDIO_PATCH_TOKEN])[0]\n        audio_start_token, audio_end_token = tokenizer.convert_tokens_to_ids([DEFAULT_AUDIO_START_TOKEN, DEFAULT_AUDIO_END_TOKEN])\n        self.model.audio_tower[0].config.audio_patch_token = audio_patch_token\n        self.model.audio_tower[0].config.audio_start_token = audio_start_token\n        self.model.audio_tower[0].config.audio_end_token = audio_end_token\n\n\nAutoConfig.register(\"llaaa\", LlaaaConfig)\nAutoModelForCausalLM.register(LlaaaConfig, LlaaaLlamaForCausalLM)\n"
  },
  {
    "path": "logger.py",
    "content": "def print_signature():\n    llasm = \"\"\"\\\n                               __    __       __         \n                              / /   / /  __ _/ _\\  /\\/\\  \n                             / /   / /  / _` \\ \\  /    \\ \n                            / /___/ /__| (_| |\\ \\/ /\\/\\ \\\\\n                            \\____/\\____/\\__,_\\__/\\/    \\/\n                             \"\"\"\n\n    logo = \"\"\"\\\n                       __ _       _     __             _ \n                      / /(_)_ __ | | __/ _\\ ___  _   _| |\n                     / / | | '_ \\| |/ /\\ \\ / _ \\| | | | |\n                    / /__| | | | |   < _\\ \\ (_) | |_| | |\n                    \\____/_|_| |_|_|\\_\\\\\\__/\\___/ \\__,_|_|\n                                                         \"\"\"\n\n    print (\"=\"*80)\n    print (llasm)\n    print (logo)\n    print (\"-\"*80)\n    print (\"Demo/HuggingFace: https://huggingface.co/spaces/LinkSoul/LLaSM\")\n    print (\"欢迎点一点 Star ^_^\")\n    print (\"=\"*80)\n\n\nif __name__ == '__main__':\n    print_signature()"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools>=61.0\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"llasm\"\nversion = \"1.0.0\"\ndescription = \"LLaSM: Large Language and Speech Model.\"\nreadme = \"README.md\"\nrequires-python = \">=3.8\"\nclassifiers = [\n    \"Programming Language :: Python :: 3\",\n    \"License :: OSI Approved :: Apache Software License\",\n]\ndependencies = [\n    \"numpy\", \"requests\",\n    \"librosa\", \"protobuf\", \"accelerate\",\n    \"tokenizers>=0.12.1\",\n    \"torch\", \"torchvision\",\n    \"transformers==4.31.0\",\n    \"sentencepiece==0.1.99\",\n]\n\n[project.urls]\n\"Homepage\" = \"https://huggingface.co/spaces/LinkSoul/LLaSM\"\n\"Bug Tracker\" = \"https://github.com/LinkSoul-AI/LLaSM/issues\"\n\n[tool.setuptools.packages.find]\nexclude = [\"assets*\", \"benchmark*\", \"docs\", \"dist*\", \"playground*\", \"scripts*\", \"tests*\"]\n\n[tool.wheel]\nexclude = [\"assets*\", \"benchmark*\", \"docs\", \"dist*\", \"playground*\", \"scripts*\", \"tests*\"]\n"
  }
]