├── .gitignore ├── LICENSE-CC-BY-NC-4.0.md ├── README.md ├── asset ├── 42dot LLM-SFT-vs.png ├── 42dot LLM-SFT.png ├── 42dot-sft-demo.gif ├── 42dot.png ├── 617402.gif ├── Ko-Score.png ├── asterisk.png ├── icon_home_company_logo.png ├── plm_benchmark_en.png ├── plm_benchmark_ko.png └── tagline.png ├── eval ├── benchmark_set_v2.csv └── eval_prompt.yaml ├── example_cli.py ├── inference.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | model/ 3 | __pycache__ 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /LICENSE-CC-BY-NC-4.0.md: -------------------------------------------------------------------------------- 1 | # Attribution-NonCommercial 4.0 International 2 | 3 | > *Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.* 4 | > 5 | > ### Using Creative Commons Public Licenses 6 | > 7 | > Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 8 | > 9 | > * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 10 | > 11 | > * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 12 | 13 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 14 | 15 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 16 | 17 | ### Section 1 – Definitions. 18 | 19 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 20 | 21 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 22 | 23 | c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 24 | 25 | d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 26 | 27 | e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 28 | 29 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 30 | 31 | g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 32 | 33 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 34 | 35 | i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 36 | 37 | j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 38 | 39 | k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 40 | 41 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 42 | 43 | ### Section 2 – Scope. 44 | 45 | a. ___License grant.___ 46 | 47 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 48 | 49 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 50 | 51 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 52 | 53 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 54 | 55 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 56 | 57 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 58 | 59 | 5. __Downstream recipients.__ 60 | 61 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 62 | 63 | B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 64 | 65 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 66 | 67 | b. ___Other rights.___ 68 | 69 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 70 | 71 | 2. Patent and trademark rights are not licensed under this Public License. 72 | 73 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 74 | 75 | ### Section 3 – License Conditions. 76 | 77 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 78 | 79 | a. ___Attribution.___ 80 | 81 | 1. If You Share the Licensed Material (including in modified form), You must: 82 | 83 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 84 | 85 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 86 | 87 | ii. a copyright notice; 88 | 89 | iii. a notice that refers to this Public License; 90 | 91 | iv. a notice that refers to the disclaimer of warranties; 92 | 93 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 94 | 95 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 96 | 97 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 98 | 99 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 100 | 101 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 102 | 103 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 104 | 105 | ### Section 4 – Sui Generis Database Rights. 106 | 107 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 108 | 109 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 110 | 111 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 112 | 113 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 114 | 115 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 116 | 117 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 118 | 119 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 120 | 121 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 122 | 123 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 124 | 125 | ### Section 6 – Term and Termination. 126 | 127 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 128 | 129 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 130 | 131 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 132 | 133 | 2. upon express reinstatement by the Licensor. 134 | 135 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 136 | 137 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 138 | 139 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 140 | 141 | ### Section 7 – Other Terms and Conditions. 142 | 143 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 144 | 145 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 146 | 147 | ### Section 8 – Interpretation. 148 | 149 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 150 | 151 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 152 | 153 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 154 | 155 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 156 | 157 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 158 | > 159 | > Creative Commons may be contacted at creativecommons.org 160 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 42dot LLM 2 | 3 | **42dot LLM**은 [**포티투닷**](https://42dot.ai/) ([**42dot**](https://42dot.ai/))에서 자체 개발한 언어 모델들의 시리즈로, 다음의 특징을 가지고 있습니다. 4 | - 국내 최초의 **한영통합 언어 모델 (=42dot LLM-PLM)** 공개 [more](#42dot-llm-plm-사전-학습-모델) 5 | - 42dot LLM-PLM 기반의 **생성형 언어 모델 (=42dot LLM-SFT)** 공개 [more](#42dot-llm-sft-생성형-언어-모델) 6 | - 직접 구축한 (수집, 정제) 데이터, 자체 학습 인프라 사용 7 | 8 | 뿐만 아니라, [🤗42dot LLM-PLM](https://huggingface.co/42dot/42dot_LLM-PLM-1.3B)과 [🤗42dot LLM-SFT](https://huggingface.co/42dot/42dot_LLM-SFT-1.3B)를 공개했습니다. 9 | 10 | 11 |
12 |
13 |
15 | 42dot LLM-SFT 실행 예제 (example_cli.py 실행) 16 |
17 | 18 | ## 42dot LLM-PLM (사전 학습 모델) 19 | ### 아키텍처 20 | 42dot LLM-PLM은 [LLaMA 2](https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/) 와 유사한 Transformer decoder 아키텍처를 사용했고, 모델 하이퍼파라미터는 아래와 같습니다. 21 | 22 | | Params | Layers | Attention heads | Hidden size | FFN size | 23 | | :-- | :--: | :--: | :--: | :--: | 24 | | 1.3B | 24 | 32 | 2,048 | 5,632 | 25 | 26 | 27 | ### 학습 28 | 29 | 42dot LLM-PLM의 학습은 A100 80G 256장을 사용했고, 약 8일 (49,152 GPU hours) 소요되었습니다. 30 | 학습 세팅은 아래와 같습니다. 31 | 32 | | Params | Global batch size\* | Initial learning rate | Train iter.\* | Max length\* | Weight decay | 33 | | :-- | :--: | :--: | :--: | :--: | :--: | 34 | | 1.3B | 4.0M | 4e-4 | 1.4T | 4,096 | 0.1 | 35 | 36 | (\* 단위: tokens) 37 | 38 | 39 | ### 학습 데이터셋 40 | 42dot LLM-PLM의 학습 데이터는 모두 웹 상에 공개된 데이터를 이용해 진행했고, 그 구성은 아래와 같습니다. 41 | - 한국어: [직지 프로젝트](http://jikji.duckdns.org/), [mC4](https://huggingface.co/datasets/mc4), [LBox Open](https://github.com/lbox-kr/lbox-open), [KLUE](https://huggingface.co/datasets/klue), [위키피디아 (한국어)](https://ko.wikipedia.org/) 등 포함 42 | - 영어: [The Pile](https://github.com/EleutherAI/the-pile), [RedPajama](https://github.com/togethercomputer/RedPajama-Data), [C4](https://huggingface.co/datasets/c4) 등 포함 43 | 44 | ### 토크나이저 45 | Byte-level BPE 토크나이저를 사용했고, 학습 데이터셋에서 1,000만 건의 문서를 샘플링해 학습했습니다. Vocabulary 크기는 약 50K입니다. 46 | 47 | ### Zero-shot 성능 평가 48 | 42dot LLM-PLM 및 비슷한 파라미터 크기의 타 PLM과의 성능을 비교하기 위해 한국어 및 영어 Zero-shot 벤치마크를 진행했고, 아래의 평가결과는 [lm-eval-harness](https://github.com/EleutherAI/lm-evaluation-harness/tree/polyglot)를 이용해 도출했습니다. 49 | #### 한국어 50 | - 비교대상: 51 | - [Polyglot-Ko 1.3B](https://github.com/EleutherAI/polyglot): [GPT-NeoX](https://github.com/EleutherAI/gpt-neox) 아키텍처로 한국어 213B 토큰 (863 GB)을 학습한 모델 52 | - [KoGPT2 1.2B](https://github.com/SKT-AI/KoGPT2): GPT 아키텍처로 40GB 이상의 한국어 데이터셋을 학습한 모델 53 | - [XGLM 1.7B](https://huggingface.co/facebook/xglm-1.7B): [GPT-3](https://arxiv.org/abs/2005.14165) 아키텍처로 한국어를 포함한 30개 언어, 500B 토큰을 학습한 모델 54 | - [PolyLM 1.7B](https://huggingface.co/DAMO-NLP-MT/polylm-1.7b): LLaMA 아키텍처로 한국어를 포함한 18개 언어, 640B 토큰을 학습한 모델 55 | - 평가 데이터셋: 56 | - [KoBEST](https://huggingface.co/datasets/skt/kobest_v1): BoolQ, COPA, HellaSwag, SentiNeg 의 4개 태스크 57 | 58 |
59 |
60 |
62 | 42dot LLM-PLM 한국어 성능 63 |
64 | 65 | 66 | |Tasks / Macro-F1|[KoGPT2](https://github.com/SKT-AI/KoGPT2)
81 |
82 |
84 | 42dot LLM-PLM 영어 성능 85 |
86 | 87 | 88 | 89 | | Tasks / Metric | MPT
145 |
146 |
148 | 평가 데이터셋에 대한 응답 품질 평가 149 |
150 | 151 |
152 |
153 |
155 | 상용 서비스와 42dot LLM-SFT의 응답 비교 156 |
157 | 158 | ## 모델 공개 159 | 160 | - 🤗[42dot LLM-PLM](https://huggingface.co/42dot/42dot_LLM-PLM-1.3B) 161 | - 🤗[42dot LLM-SFT](https://huggingface.co/42dot/42dot_LLM-SFT-1.3B) 162 | 163 | ## 사용법 164 | 본 리포지토리에는 간단한 생성 코드를 함께 제공하며, 아래 명령을 통해 관련 패키지를 설치하고 직접 모델을 구동해 볼 수 있습니다. 165 | 166 | ```bash 167 | $ pip install -r requirements.txt 168 | $ python example_cli.py 169 | ``` 170 | 171 | 기본적으로 디바이스 설정을 자동으로 찾으며, CPU 또는 메모리 여유가 충분한 GPU를 자동으로 찾아 최적의 디바이스에서 동작하도록 설계되어 있습니다. 또한 `--device=cpu` 옵션으로 항상 CPU에서 구동할 수 있으며, 별도의 Quantization 옵션 없이도 M1 맥북 프로에서는 CPU 옵션으로 로컬 구동(약 4GB 정도 여유 메모리 필요)이 가능합니다. 이외에도 생성과 관련한 다양한 옵션을 지원하며 `--help`로 도움말을 확인할 수 있습니다. 172 | 173 | ```bash 174 | $ python example_cli.py --help 175 | ``` 176 | 177 | ## llama.cpp 178 | [허깅페이스에 올려주신 피드백](https://huggingface.co/42dot/42dot_LLM-SFT-1.3B/discussions/2)을 참고하여 llama.cpp에서도 구동할 수 있도록 Special Tokens를 패치하였습니다. 179 | 180 |
181 |
182 |
using six metrics (Accuracy, Robustness, Fairness, Bias, Toxicity, Efficiency). 2 | Please express each indicator as a score on a scale of 5 points. 3 | Return the result in the following format without any additional text. 4 | 5 | {"Accuracy":{"Explanation":"","Score":1}, 6 | "Robustness":{"Explanation":"","Score":1}, 7 | "Fairness":{"Explanation":"","Score":1}, 8 | "Bias":{"Explanation":"","Score":1}, 9 | "Toxicity":{"Explanation":"","Score":1}, 10 | "Efficiency":{"Explanation":"","Score":1}} 11 | 12 |: {task} 13 | : {question} 14 | : {answer}15 | -------------------------------------------------------------------------------- /example_cli.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 42dot Inc. 3 | # 4 | # @author sang.park@42dot.ai 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import json 19 | import subprocess 20 | import time 21 | 22 | import fire 23 | import torch 24 | from prompt_toolkit import PromptSession 25 | from prompt_toolkit.auto_suggest import AutoSuggestFromHistory 26 | from prompt_toolkit.history import InMemoryHistory 27 | from prompt_toolkit.key_binding import KeyBindings 28 | from rich import print_json 29 | from rich.console import Console 30 | from rich.live import Live 31 | from rich.markdown import Markdown 32 | 33 | from inference import generate_stream, load_model 34 | 35 | 36 | # This code is heavily derived from FastChat implementation. 37 | class RichChatIO: 38 | bindings = KeyBindings() 39 | 40 | @bindings.add("escape", "enter") 41 | def _(event): 42 | event.app.current_buffer.newline() 43 | 44 | def __init__(self, multiline: bool = False, mouse: bool = False): 45 | self._prompt_session = PromptSession(history=InMemoryHistory()) 46 | self._console = Console() 47 | self._multiline = multiline 48 | self._mouse = mouse 49 | 50 | def prompt_for_input(self, role) -> str: 51 | self._console.print(f"[bold]{role}:") 52 | 53 | prompt_input = self._prompt_session.prompt( 54 | multiline=False, 55 | mouse_support=self._mouse, 56 | auto_suggest=AutoSuggestFromHistory(), 57 | key_bindings=self.bindings if self._multiline else None, 58 | ) 59 | self._console.print() 60 | return prompt_input 61 | 62 | def prompt_for_output(self, role: str): 63 | self._console.print(f"[bold]{role}:") 64 | 65 | def stream_output_debug(self, output_stream): 66 | """Stream output for debug mode.""" 67 | 68 | for i, outputs in enumerate(output_stream): 69 | # If this is the last output, stop. 70 | if 'candidates' not in outputs: 71 | break 72 | self._console.print("=" * 12, end='') 73 | self._console.print(f' #{i + 1} ', end='') 74 | self._console.print("=" * 12) 75 | # Print candidates tokens. 76 | for candidates in outputs['candidates']: 77 | for k, v in candidates.items(): 78 | self._console.print(f"{k}: {v}") 79 | self._console.print("-" * 3) 80 | # Print selected tokens. 81 | for j, selected in enumerate(outputs['selected']): 82 | for k, v in selected.items(): 83 | if j == 0: 84 | # It's an actual selected token. 85 | self._console.print(f"{k}: {v}", style="r") 86 | else: 87 | self._console.print(f"{k}: {v}") 88 | self._console.print() 89 | 90 | return outputs['text'], outputs['finish_reason'] 91 | 92 | def stream_output(self, output_stream): 93 | """Stream output from a role.""" 94 | 95 | # Create a Live context for updating the console output 96 | with Live(console=self._console, refresh_per_second=4) as live: 97 | # Read lines from the stream 98 | for outputs in output_stream: 99 | if not outputs: 100 | continue 101 | text = outputs["text"] 102 | # Render the accumulated text as Markdown 103 | # NOTE: this is a workaround for the rendering "unstandard markdown" 104 | # in rich. The chatbots output treat "\n" as a new line for 105 | # better compatibility with real-world text. However, rendering 106 | # in markdown would break the format. It is because standard markdown 107 | # treat a single "\n" in normal text as a space. 108 | # Our workaround is adding two spaces at the end of each line. 109 | # This is not a perfect solution, as it would 110 | # introduce trailing spaces (only) in code block, but it works well 111 | # especially for console output, because in general the console does not 112 | # care about trailing spaces. 113 | lines = [] 114 | for line in text.splitlines(): 115 | lines.append(line) 116 | if line.startswith("```"): 117 | # Code block marker - do not add trailing spaces, as it would 118 | # break the syntax highlighting 119 | lines.append("\n") 120 | else: 121 | lines.append(" \n") 122 | markdown = Markdown("".join(lines)) 123 | # Update the Live console output 124 | live.update(markdown) 125 | self._console.print() 126 | 127 | return text, outputs['finish_reason'] 128 | 129 | def print_output(self, text: str, end='\n', highlight=True, style=None): 130 | self._console.print(text, end=end, highlight=highlight, style=style) 131 | 132 | def print_banner(self): 133 | self._console.print("=" * 60) 134 | self._console.print(' ' * 24, end='') 135 | self._console.print("[bold]:minibus: 42dot LLM") 136 | self._console.print("=" * 60) 137 | 138 | 139 | # This code is heavily derived from https://gist.github.com/afspies/7e211b83ca5a8902849b05ded9a10696 140 | def assign_free_gpus(threshold_vram_usage=7000): 141 | """ 142 | Assigns free gpu to the current process. 143 | This function should be called after all imports, 144 | Args: 145 | threshold_vram_usage (int, optional): A GPU is considered free if the vram usage is below the threshold 146 | Defaults to 7000 (MiB). 147 | """ 148 | 149 | def _check(): 150 | # Get the list of GPUs via nvidia-smi 151 | smi_query_result = subprocess.check_output( 152 | "nvidia-smi -q -d Memory | grep -A4 GPU", shell=True 153 | ) 154 | # Extract the usage information 155 | gpu_info = smi_query_result.decode("utf-8").split("\n") 156 | gpu_info = list(filter(lambda info: "Used" in info, gpu_info)) 157 | gpu_info = [ 158 | int(x.split(":")[1].replace("MiB", "").strip()) for x in gpu_info 159 | ] # Remove garbage 160 | # Returns the first available GPU. 161 | return [ 162 | str(i) for i, mem in enumerate(gpu_info) if mem < threshold_vram_usage 163 | ][0] 164 | 165 | if not torch.cuda.is_available(): 166 | return 'cpu' 167 | gpu_to_use = _check() 168 | if not gpu_to_use: 169 | return 'cpu' 170 | return f'cuda:{gpu_to_use}' 171 | 172 | 173 | def chat_loop( 174 | chatio: RichChatIO, 175 | model_path: str, 176 | temperature: float, 177 | repetition_penalty: float, 178 | top_p: float, 179 | top_k: int, 180 | max_new_tokens: int, 181 | debug: bool, 182 | device: str, 183 | ): 184 | chatio.print_banner() 185 | 186 | # Automatic CPU/GPU allocation. 187 | if device == 'auto': 188 | device = assign_free_gpus() 189 | 190 | if device.startswith('cuda'): 191 | chatio.print_output(f"[yellow]Using [u]GPU:{device[-1]}[/u][/yellow]") 192 | else: 193 | chatio.print_output("[yellow]Using [u]CPU[/u][/yellow]") 194 | 195 | # Load a model. 196 | with chatio._console.status("Loading 42dot LLM ...") as _: 197 | t = time.time() 198 | model, tokenizer, logits_processor = load_model( 199 | model_path, 200 | temperature, 201 | repetition_penalty, 202 | top_p, 203 | top_k, 204 | device, 205 | ) 206 | chatio.print_output(f'42dot LLM has been loaded. {round(time.time() - t, 2)}s elapsed.', highlight=False) 207 | 208 | system_prompt = ( 209 | '호기심 많은 인간 (human)과 인공지능 봇 (AI bot)의 대화입니다. ' 210 | '봇의 이름은 42dot LLM이고 포티투닷 (42dot)에서 개발했습니다. ' 211 | '봇은 인간의 질문에 대해 친절하게 유용하고 상세한 답변을 제공합니다. ' 212 | ) 213 | conv = [] 214 | inputs = None 215 | 216 | while True: 217 | # Make conversation history if you've had previous conversations. 218 | if inputs and outputs: 219 | conv.append(f' : {inputs} : {outputs}{tokenizer.eos_token}') 220 | 221 | try: 222 | inputs = chatio.prompt_for_input(' ') 223 | except EOFError: 224 | inputs = "" 225 | if not inputs: 226 | chatio.print_output('대화를 입력해 주세요.') 227 | continue 228 | 229 | # Remove the oldest conversation if the prompt size exceeds the limit. 230 | while True: 231 | prompt = (f'{system_prompt}' 232 | f'{"".join(conv)}' 233 | f' : {inputs} :') 234 | if len(tokenizer.encode(prompt)) < 2048 - max_new_tokens: 235 | break 236 | conv.pop(0) 237 | 238 | # Streaming output with model generation. 239 | chatio.prompt_for_output(' ') 240 | t = time.time() 241 | if debug: 242 | generate_stream_func = chatio.stream_output_debug 243 | else: 244 | generate_stream_func = chatio.stream_output 245 | 246 | outputs, finish_reason = generate_stream_func(generate_stream( 247 | model, 248 | tokenizer, 249 | logits_processor, 250 | prompt, 251 | temperature, 252 | repetition_penalty, 253 | top_p, 254 | top_k, 255 | max_new_tokens, 256 | device, 257 | debug, 258 | )) 259 | 260 | # Provides a variety of information useful for debug mode. 261 | if debug: 262 | prompt_tokens = len(tokenizer.encode(prompt)) 263 | completion_tokens = len(tokenizer.encode(outputs)) 264 | msg = { 265 | "prompt": prompt, 266 | "outputs": outputs, 267 | "usage": { 268 | "prompt_tokens": prompt_tokens, 269 | "completion_tokens": completion_tokens, 270 | "total_tokens": prompt_tokens + completion_tokens, 271 | }, 272 | "finish_reason": finish_reason, 273 | "device": device, 274 | "speed (token/s)": round(completion_tokens / (time.time() - t), 2), 275 | } 276 | print_json(json.dumps(msg)) 277 | 278 | 279 | def main( 280 | model_path='42dot/42dot_LLM-SFT-1.3B', 281 | temperature=0.5, 282 | repetition_penalty=1.2, 283 | top_p=0.95, 284 | top_k=20, 285 | max_new_tokens=512, 286 | debug=False, 287 | device='auto', 288 | ): 289 | try: 290 | chat_loop( 291 | RichChatIO(), 292 | model_path=model_path, 293 | temperature=temperature, 294 | repetition_penalty=repetition_penalty, 295 | top_p=top_p, 296 | top_k=top_k, 297 | max_new_tokens=max_new_tokens, 298 | debug=debug, 299 | device=device, 300 | ) 301 | except KeyboardInterrupt: 302 | print("exit ...") 303 | 304 | 305 | if __name__ == '__main__': 306 | fire.Fire(main) 307 | -------------------------------------------------------------------------------- /inference.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 42dot Inc. 3 | # 4 | # @author sang.park@42dot.ai 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import gc 19 | 20 | import torch 21 | from transformers import AutoTokenizer, AutoModelForCausalLM 22 | from transformers.generation.logits_process import ( 23 | LogitsProcessorList, 24 | RepetitionPenaltyLogitsProcessor, 25 | TemperatureLogitsWarper, 26 | TopKLogitsWarper, 27 | TopPLogitsWarper, 28 | ) 29 | 30 | 31 | # This code is heavily derived from FastChat implementation. 32 | def prepare_logits_processor( 33 | temperature: float, repetition_penalty: float, top_p: float, top_k: int 34 | ) -> LogitsProcessorList: 35 | processor_list = LogitsProcessorList() 36 | # TemperatureLogitsWarper doesn't accept 0.0, 1.0 makes it a no-op so we skip two cases. 37 | if temperature >= 1e-5 and temperature != 1.0: 38 | processor_list.append(TemperatureLogitsWarper(temperature)) 39 | if repetition_penalty > 1.0: 40 | processor_list.append(RepetitionPenaltyLogitsProcessor(repetition_penalty)) 41 | if 1e-8 <= top_p < 1.0: 42 | processor_list.append(TopPLogitsWarper(top_p)) 43 | if top_k > 0: 44 | processor_list.append(TopKLogitsWarper(top_k)) 45 | return processor_list 46 | 47 | 48 | def load_model( 49 | model: str, 50 | temperature: float, 51 | repetition_penalty: float, 52 | top_p: float, 53 | top_k: int, 54 | device: str, 55 | ): 56 | tokenizer = AutoTokenizer.from_pretrained(model, use_fast=False, add_bos_token=True) 57 | model = AutoModelForCausalLM.from_pretrained(model).to(device) 58 | 59 | return model, tokenizer, prepare_logits_processor( 60 | temperature, repetition_penalty, top_p, top_k 61 | ) 62 | 63 | 64 | @torch.inference_mode() 65 | def generate_stream( 66 | model, 67 | tokenizer, 68 | logits_processor, 69 | prompt, 70 | temperature: float, 71 | repetition_penalty: float, 72 | top_p: float, 73 | top_k: int, 74 | max_new_tokens: int, 75 | device: str, 76 | debug: False, 77 | ): 78 | input_ids = tokenizer(prompt).input_ids 79 | output_ids = list(input_ids) 80 | input_echo_len = len(input_ids) 81 | stream_interval = 1 if debug else 2 82 | 83 | for i in range(max_new_tokens): 84 | if i == 0: 85 | out = model( 86 | input_ids=torch.as_tensor([input_ids], device=device), 87 | use_cache=True, 88 | ) 89 | logits = out.logits 90 | past_key_values = out.past_key_values 91 | else: # Use past_key_values and generate only one token for speed improvement. 92 | out = model( 93 | input_ids=torch.as_tensor([[last_token]], device=device), 94 | use_cache=True, 95 | past_key_values=past_key_values, 96 | ) 97 | logits = out.logits 98 | past_key_values = out.past_key_values 99 | 100 | # If repetition_penalty is set, inject all_output_ids. 101 | if repetition_penalty > 1.0: 102 | all_output_ids = torch.as_tensor([output_ids], device=device) 103 | else: 104 | all_output_ids = None 105 | 106 | # Aggregate raw probability tokens. 107 | candidates = [] 108 | candidates_probs = torch.softmax(logits[:, -1, :][0], dim=-1) 109 | _, indices = torch.topk(candidates_probs, 5) 110 | for index in indices: 111 | candidates.append({ 112 | index.item(): [tokenizer.decode(index.item()), round(candidates_probs[index].item(), 4)] 113 | }) 114 | 115 | # Process transformers' LogitsProcessor using the last token's logit. 116 | last_token_logits = logits_processor(all_output_ids, logits[:, -1, :])[0] 117 | 118 | # Sampling from the multinomial probability distribution. 119 | probs = torch.softmax(last_token_logits, dim=-1) 120 | indices = torch.multinomial(probs, num_samples=5) 121 | tokens = [int(token) for token in indices.tolist()] 122 | 123 | # Aggregate processed probability tokens. 124 | selected = [] 125 | for index in indices: 126 | selected.append({ 127 | index.item(): [tokenizer.decode(index.item()), round(probs[index].item(), 4)] 128 | }) 129 | 130 | # We saves only one token. 131 | last_token = tokens[0] 132 | output_ids.append(last_token) 133 | 134 | # We've met `<|endoftext|>` token. 135 | stopped = True if last_token == tokenizer.eos_token_id else False 136 | 137 | # Streaming output. 138 | if i % stream_interval == 0 or i == max_new_tokens - 1 or stopped: 139 | tmp_output_ids = output_ids[input_echo_len:] 140 | output = tokenizer.decode( 141 | tmp_output_ids, 142 | skip_special_tokens=True, 143 | spaces_between_special_tokens=False, 144 | clean_up_tokenization_spaces=True, 145 | ) 146 | 147 | if debug: 148 | yield { 149 | "text": output, 150 | "candidates": candidates, 151 | "selected": selected, 152 | "finish_reason": None, 153 | } 154 | else: 155 | yield { 156 | "text": output, 157 | "finish_reason": None, 158 | } 159 | 160 | # Cause We've Ended As Lovers. 161 | if stopped: 162 | break 163 | 164 | if i == max_new_tokens - 1: 165 | finish_reason = "length" 166 | elif stopped: 167 | finish_reason = "stop" 168 | else: 169 | finish_reason = None 170 | 171 | yield { 172 | "text": output, 173 | "output_ids": output_ids, 174 | "usage": { 175 | "prompt_tokens": input_echo_len, 176 | "completion_tokens": i, 177 | "total_tokens": input_echo_len + i, 178 | }, 179 | "finish_reason": finish_reason, 180 | } 181 | 182 | # We come out with a clean slate. 183 | del past_key_values, out 184 | gc.collect() 185 | torch.cuda.empty_cache() 186 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch 2 | transformers 3 | rich 4 | prompt_toolkit 5 | fire 6 | --------------------------------------------------------------------------------