e-mon commited on
Commit
6bc4588
1 Parent(s): 842b6ca

delete files

Browse files
Files changed (8) hide show
  1. LICENSE.txt +0 -126
  2. USE_POLICY.md +0 -50
  3. app.py +0 -552
  4. key_visual.png +0 -3
  5. llama_face.png +0 -3
  6. model_vllm.py +0 -115
  7. person_face.png +0 -3
  8. requirements.txt +0 -153
LICENSE.txt DELETED
@@ -1,126 +0,0 @@
1
- LLAMA 2 COMMUNITY LICENSE AGREEMENT
2
- Llama 2 Version Release Date: July 18, 2023
3
-
4
- "Agreement" means the terms and conditions for use, reproduction, distribution and
5
- modification of the Llama Materials set forth herein.
6
-
7
- "Documentation" means the specifications, manuals and documentation
8
- accompanying Llama 2 distributed by Meta at ai.meta.com/resources/models-and-
9
- libraries/llama-downloads/.
10
-
11
- "Licensee" or "you" means you, or your employer or any other person or entity (if
12
- you are entering into this Agreement on such person or entity's behalf), of the age
13
- required under applicable laws, rules or regulations to provide legal consent and that
14
- has legal authority to bind your employer or such other person or entity if you are
15
- entering in this Agreement on their behalf.
16
-
17
- "Llama 2" means the foundational large language models and software and
18
- algorithms, including machine-learning model code, trained model weights,
19
- inference-enabling code, training-enabling code, fine-tuning enabling code and other
20
- elements of the foregoing distributed by Meta at ai.meta.com/resources/models-and-
21
- libraries/llama-downloads/.
22
-
23
- "Llama Materials" means, collectively, Meta's proprietary Llama 2 and
24
- Documentation (and any portion thereof) made available under this Agreement.
25
-
26
- "Meta" or "we" means Meta Platforms Ireland Limited (if you are located in or, if you
27
- are an entity, your principal place of business is in the EEA or Switzerland) and Meta
28
- Platforms, Inc. (if you are located outside of the EEA or Switzerland).
29
-
30
- By clicking "I Accept" below or by using or distributing any portion or element of the
31
- Llama Materials, you agree to be bound by this Agreement.
32
-
33
- 1. License Rights and Redistribution.
34
-
35
- a. Grant of Rights. You are granted a non-exclusive, worldwide, non-
36
- transferable and royalty-free limited license under Meta's intellectual property or
37
- other rights owned by Meta embodied in the Llama Materials to use, reproduce,
38
- distribute, copy, create derivative works of, and make modifications to the Llama
39
- Materials.
40
-
41
- b. Redistribution and Use.
42
-
43
- i. If you distribute or make the Llama Materials, or any derivative works
44
- thereof, available to a third party, you shall provide a copy of this Agreement to such
45
- third party.
46
- ii. If you receive Llama Materials, or any derivative works thereof, from
47
- a Licensee as part of an integrated end user product, then Section 2 of this
48
- Agreement will not apply to you.
49
-
50
- iii. You must retain in all copies of the Llama Materials that you
51
- distribute the following attribution notice within a "Notice" text file distributed as a
52
- part of such copies: "Llama 2 is licensed under the LLAMA 2 Community License,
53
- Copyright (c) Meta Platforms, Inc. All Rights Reserved."
54
-
55
- iv. Your use of the Llama Materials must comply with applicable laws
56
- and regulations (including trade compliance laws and regulations) and adhere to the
57
- Acceptable Use Policy for the Llama Materials (available at
58
- https://ai.meta.com/llama/use-policy), which is hereby incorporated by reference into
59
- this Agreement.
60
-
61
- v. You will not use the Llama Materials or any output or results of the
62
- Llama Materials to improve any other large language model (excluding Llama 2 or
63
- derivative works thereof).
64
-
65
- 2. Additional Commercial Terms. If, on the Llama 2 version release date, the
66
- monthly active users of the products or services made available by or for Licensee,
67
- or Licensee's affiliates, is greater than 700 million monthly active users in the
68
- preceding calendar month, you must request a license from Meta, which Meta may
69
- grant to you in its sole discretion, and you are not authorized to exercise any of the
70
- rights under this Agreement unless or until Meta otherwise expressly grants you
71
- such rights.
72
-
73
- 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE
74
- LLAMA MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE
75
- PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
76
- EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY
77
- WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR
78
- FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE
79
- FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING
80
- THE LLAMA MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR
81
- USE OF THE LLAMA MATERIALS AND ANY OUTPUT AND RESULTS.
82
-
83
- 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE
84
- LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT,
85
- NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS
86
- AGREEMENT, FOR ANY LOST PROFITS OR ANY INDIRECT, SPECIAL,
87
- CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN
88
- IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF
89
- ANY OF THE FOREGOING.
90
-
91
- 5. Intellectual Property.
92
-
93
- a. No trademark licenses are granted under this Agreement, and in
94
- connection with the Llama Materials, neither Meta nor Licensee may use any name
95
- or mark owned by or associated with the other or any of its affiliates, except as
96
- required for reasonable and customary use in describing and redistributing the
97
- Llama Materials.
98
-
99
- b. Subject to Meta's ownership of Llama Materials and derivatives made by or
100
- for Meta, with respect to any derivative works and modifications of the Llama
101
- Materials that are made by you, as between you and Meta, you are and will be the
102
- owner of such derivative works and modifications.
103
-
104
- c. If you institute litigation or other proceedings against Meta or any entity
105
- (including a cross-claim or counterclaim in a lawsuit) alleging that the Llama
106
- Materials or Llama 2 outputs or results, or any portion of any of the foregoing,
107
- constitutes infringement of intellectual property or other rights owned or licensable
108
- by you, then any licenses granted to you under this Agreement shall terminate as of
109
- the date such litigation or claim is filed or instituted. You will indemnify and hold
110
- harmless Meta from and against any claim by any third party arising out of or related
111
- to your use or distribution of the Llama Materials.
112
-
113
- 6. Term and Termination. The term of this Agreement will commence upon your
114
- acceptance of this Agreement or access to the Llama Materials and will continue in
115
- full force and effect until terminated in accordance with the terms and conditions
116
- herein. Meta may terminate this Agreement if you are in breach of any term or
117
- condition of this Agreement. Upon termination of this Agreement, you shall delete
118
- and cease use of the Llama Materials. Sections 3, 4 and 7 shall survive the
119
- termination of this Agreement.
120
-
121
- 7. Governing Law and Jurisdiction. This Agreement will be governed and
122
- construed under the laws of the State of California without regard to choice of law
123
- principles, and the UN Convention on Contracts for the International Sale of Goods
124
- does not apply to this Agreement. The courts of California shall have exclusive
125
- jurisdiction of any dispute arising out of this Agreement.
126
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
USE_POLICY.md DELETED
@@ -1,50 +0,0 @@
1
- # Llama 2 Acceptable Use Policy
2
-
3
- Meta is committed to promoting safe and fair use of its tools and features, including Llama 2. If you access or use Llama 2, you agree to this Acceptable Use Policy (“Policy”). The most recent copy of this policy can be found at [ai.meta.com/llama/use-policy](http://ai.meta.com/llama/use-policy).
4
-
5
- ## Prohibited Uses
6
- We want everyone to use Llama 2 safely and responsibly. You agree you will not use, or allow others to use, Llama 2 to:
7
-
8
- 1. Violate the law or others’ rights, including to:
9
- 1. Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:
10
- 1. Violence or terrorism
11
- 2. Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material
12
- 3. Human trafficking, exploitation, and sexual violence
13
- 4. The illegal distribution of information or materials to minors, including obscene materials, or failure to employ legally required age-gating in connection with such information or materials.
14
- 5. Sexual solicitation
15
- 6. Any other criminal activity
16
- 2. Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
17
- 3. Engage in, promote, incite, or facilitate discrimination or other unlawful or harmful conduct in the provision of employment, employment benefits, credit, housing, other economic benefits, or other essential goods and services
18
- 4. Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
19
- 5. Collect, process, disclose, generate, or infer health, demographic, or other sensitive personal or private information about individuals without rights and consents required by applicable laws
20
- 6. Engage in or facilitate any action or generate any content that infringes, misappropriates, or otherwise violates any third-party rights, including the outputs or results of any products or services using the Llama 2 Materials
21
- 7. Create, generate, or facilitate the creation of malicious code, malware, computer viruses or do anything else that could disable, overburden, interfere with or impair the proper working, integrity, operation or appearance of a website or computer system
22
-
23
-
24
-
25
- 2. Engage in, promote, incite, facilitate, or assist in the planning or development of activities that present a risk of death or bodily harm to individuals, including use of Llama 2 related to the following:
26
- 1. Military, warfare, nuclear industries or applications, espionage, use for materials or activities that are subject to the International Traffic Arms Regulations (ITAR) maintained by the United States Department of State
27
- 2. Guns and illegal weapons (including weapon development)
28
- 3. Illegal drugs and regulated/controlled substances
29
- 4. Operation of critical infrastructure, transportation technologies, or heavy machinery
30
- 5. Self-harm or harm to others, including suicide, cutting, and eating disorders
31
- 6. Any content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual
32
-
33
-
34
-
35
- 3. Intentionally deceive or mislead others, including use of Llama 2 related to the following:
36
- 1. Generating, promoting, or furthering fraud or the creation or promotion of disinformation
37
- 2. Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
38
- 3. Generating, promoting, or further distributing spam
39
- 4. Impersonating another individual without consent, authorization, or legal right
40
- 5. Representing that the use of Llama 2 or outputs are human-generated
41
- 6. Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement
42
- 4. Fail to appropriately disclose to end users any known dangers of your AI system
43
-
44
- Please report any violation of this Policy, software “bug,” or other problems that could lead to a violation of this Policy through one of the following means:
45
-
46
- * Reporting issues with the model: [github.com/facebookresearch/llama](http://github.com/facebookresearch/llama)
47
- * Reporting risky content generated by the model: [developers.facebook.com/llama_output_feedback](http://developers.facebook.com/llama_output_feedback)
48
- * Reporting bugs and security concerns: [facebook.com/whitehat/info](http://facebook.com/whitehat/info)
49
- * Reporting violations of the Acceptable Use Policy or unlicensed uses of Llama: [LlamaUseReport@meta.com](mailto:LlamaUseReport@meta.com)
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py DELETED
@@ -1,552 +0,0 @@
1
- from datetime import datetime, timezone, timedelta
2
- import os
3
- import time
4
- from typing import AsyncGenerator
5
- import uuid
6
- import asyncio
7
- import logging
8
- import textwrap
9
-
10
- import boto3
11
- from botocore.config import Config
12
- import gradio as gr
13
- import pandas as pd
14
- import torch
15
-
16
- from model_vllm import get_input_token_length, run
17
-
18
- logging.basicConfig(encoding='utf-8', level=logging.ERROR)
19
- logger = logging.getLogger(__name__)
20
-
21
- JST = timezone(timedelta(hours=+9), 'JST')
22
-
23
- DEFAULT_SYSTEM_PROMPT = 'あなたは誠実で優秀な日本人のアシスタントです。'
24
- MAX_MAX_NEW_TOKENS = 2048
25
- DEFAULT_MAX_NEW_TOKENS = 512
26
- MAX_INPUT_TOKEN_LENGTH = 4000
27
-
28
- TITLE = '# ELYZA-japanese-Llama-2-13b-instruct'
29
- DESCRIPTION = """
30
- ## 概要
31
- - [ELYZA-japanese-Llama-2-13b](https://huggingface.co/elyza/ELYZA-japanese-Llama-2-13b)は、[株式会社ELYZA](https://elyza.ai/) (以降「当社」と呼称) が[Llama2](https://ai.meta.com/llama/)をベースとして日本語能力を拡張するために事前学習を行ったモデルです。
32
- - [ELYZA-japanese-Llama-2-13b-instruct](https://huggingface.co/elyza/ELYZA-japanese-Llama-2-13b-instruct)は ELYZA-japanese-Llama-2-13b を弊社独自のinstruction tuning用データセットで事後学習したモデルです。
33
- - 本デモではこのモデルが使われています。
34
- - 詳細は[Blog記事](https://note.com/elyza/n/n5d42686b60b7)を参照してください。
35
- - 本デモではこちらの[Llama-2 7B Chat](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat)のデモをベースにさせていただきました。
36
-
37
- ## License
38
- - Llama 2 is licensed under the LLAMA 2 Community License, Copyright (c) Meta Platforms, Inc. All Rights Reserved.
39
-
40
- ## 免責事項
41
- - 当社は、本デモについて、ユーザーの特定の目的に適合すること、期待する機能・正確性・有用性を有すること、出力データが完全性、正確性、有用性を有すること、ユーザーによる本サービスの利用がユーザーに適用のある法令等に適合すること、継続的に利用できること、及び不具合が生じないことについて、明示又は黙示を問わず何ら保証するものではありません。
42
- - 当社は、本デモに関してユーザーが被った損害等につき、一切の責任を負わないものとし、ユーザーはあらかじめこれを承諾するものとします。
43
- - 当社は、本デモを通じて、ユーザー又は第三者の個人情報を取得することを想定しておらず、ユーザーは、本デモに、ユーザー又は第三者の氏名その他の特定の個人を識別することができる情報等を入力等してはならないものとします。
44
- - ユーザーは、当社が本デモ又は本デモに使用されているアルゴリズム等の改善・向上に使用することを許諾するものとします。
45
-
46
- ## 本デモで入力・出力されたデータの記録・利用に関して
47
- - 本デモで入力・出力されたデータは当社にて記録させていただき、今後の本デモ又は本デモに使用されているアルゴリズム等の改善・向上に使用させていただく場合がございます。
48
-
49
- ## We are hiring!
50
- - 当社 (株式会社ELYZA) に興味のある方、ぜひお話ししませんか?
51
- - 機械学習エンジニア・インターン募集: https://open.talentio.com/r/1/c/elyza/homes/2507
52
- - カジュアル面談はこちら: https://chillout.elyza.ai/elyza-japanese-llama2-13b
53
- """
54
-
55
- _format_example = lambda s: textwrap.dedent(s).strip()
56
-
57
- examples = list(map(_format_example, [
58
- """
59
- 「キムチプリン」という新商品を考えています。この商品に対する世間の意見として想像されるものを箇条書きで3つ教えて
60
- """,
61
- """
62
- 「メタリック」から「気分上々」までが自然につながるように、あいだの単語を連想してください。
63
- """,
64
- """
65
- 自律神経や副交感神経が乱れている、とはどのような状態ですか?科学的に教えて
66
- """,
67
- """
68
- 日本国内で観光に行きたいと思っています。東京、名古屋、大阪、京都、福岡の特徴を表にまとめてください。
69
- 列名は「都道府県」「おすすめスポット」「おすすめグルメ」にしてください。
70
- """,
71
- """
72
- 私の考えた創作料理について、想像して説明を書いてください。
73
-
74
- 1. トマトマット
75
- 2. 餃子風もやし炒め
76
- 3. おにぎりすぎ
77
- """,
78
- ]))
79
-
80
- if not torch.cuda.is_available():
81
- DESCRIPTION += '\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>'
82
-
83
- try:
84
- s3 = boto3.client(
85
- 's3',
86
- aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],
87
- aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'],
88
- region_name=os.environ['S3_REGION'],
89
- config=Config(
90
- connect_timeout=5,
91
- read_timeout=5,
92
- retries={
93
- 'mode': 'standard',
94
- 'total_max_attempts': 3,
95
- },
96
- ),
97
- )
98
- except Exception:
99
- logger.exception('Failed to initialize S3 client')
100
-
101
-
102
- def clear_and_save_textbox(message: str) -> tuple[str, str]:
103
- return '', message
104
-
105
-
106
- def display_input(message: str, history: list[tuple[str, str]]) -> list[tuple[str, str]]:
107
- history.append((message, ''))
108
- return history
109
-
110
-
111
- def delete_prev_fn(history: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], str]:
112
- try:
113
- message, _ = history.pop()
114
- except IndexError:
115
- message = ''
116
- return history, message or ''
117
-
118
-
119
- async def generate(
120
- message: str,
121
- history_with_input: list[tuple[str, str]],
122
- system_prompt: str,
123
- max_new_tokens: int,
124
- temperature: float,
125
- top_p: float,
126
- top_k: int,
127
- do_sample: bool,
128
- repetition_penalty: float,
129
- ) -> AsyncGenerator[list[tuple[str, str]], None]:
130
- if max_new_tokens > MAX_MAX_NEW_TOKENS:
131
- raise ValueError
132
-
133
- history = history_with_input[:-1]
134
- stream = await run(
135
- message=message,
136
- chat_history=history,
137
- system_prompt=system_prompt,
138
- max_new_tokens=max_new_tokens,
139
- temperature=float(temperature),
140
- top_p=float(top_p),
141
- top_k=top_k,
142
- do_sample=do_sample,
143
- repetition_penalty=float(repetition_penalty),
144
- stream=True,
145
- )
146
- async for response in stream:
147
- yield history + [(message, response)]
148
-
149
-
150
- def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
151
- response = asyncio.run(run(
152
- message=message,
153
- chat_history=[],
154
- system_prompt=DEFAULT_SYSTEM_PROMPT,
155
- max_new_tokens=DEFAULT_MAX_NEW_TOKENS,
156
- temperature=1,
157
- top_p=0.95,
158
- top_k=50,
159
- do_sample=False,
160
- repetition_penalty=1.0,
161
- stream=False
162
- ))
163
-
164
- return '', [(message, response)]
165
-
166
- def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
167
- input_token_length = get_input_token_length(message, chat_history, system_prompt)
168
- if input_token_length > MAX_INPUT_TOKEN_LENGTH:
169
- raise gr.Error(
170
- f'合計対話長が長すぎます ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH})。入力文章を短くするか、「🗑️ これまでの出力を消す」ボタンを押してから再実行してください。'
171
- )
172
-
173
- if len(message) <= 0:
174
- raise gr.Error('入力が空です。1文字以上の文字列を入力してください。')
175
-
176
-
177
- def convert_history_to_str(history: list[tuple[str, str]]) -> str:
178
- res = []
179
- for user_utt, sys_utt in history:
180
- res.append(f'😃: {user_utt}')
181
- res.append(f'🤖: {sys_utt}')
182
- return '<br>'.join(res)
183
-
184
-
185
- def output_log(history: list[tuple[str, str]], uuid_list: list[tuple[str, str]]) -> None:
186
- tree_uuid = uuid_list[0][0]
187
- last_messages = history[-1]
188
- last_uuids = uuid_list[-1]
189
- parent_uuid = None
190
- record_message = None
191
- record_uuid = None
192
- role = None
193
- if last_uuids[1] == '':
194
- role = 'user'
195
- record_message = last_messages[0]
196
- record_uuid = last_uuids[0]
197
- if len(history) >= 2:
198
- parent_uuid = uuid_list[-2][1]
199
- else:
200
- parent_uuid = last_uuids[0]
201
- else:
202
- role = 'assistant'
203
- record_message = last_messages[1]
204
- record_uuid = last_uuids[1]
205
- parent_uuid = last_uuids[0]
206
-
207
- now = datetime.fromtimestamp(time.time(), JST)
208
- yyyymmdd = now.strftime('%Y%m%d')
209
- created_at = now.strftime('%Y-%m-%d %H:%M:%S.%f')
210
-
211
- d = {
212
- 'created_at': created_at,
213
- 'tree_uuid': tree_uuid,
214
- 'parent_uuid': parent_uuid,
215
- 'uuid': record_uuid,
216
- 'role': role,
217
- 'message': record_message,
218
- }
219
- try:
220
- csv_buffer = pd.DataFrame(d, index=[0]).to_csv(index=None)
221
- s3.put_object(
222
- Bucket=os.environ['S3_BUCKET'],
223
- Key=f"{os.environ['S3_KEY_PREFIX']}/{yyyymmdd}/{record_uuid}.csv",
224
- Body=csv_buffer,
225
- )
226
- except Exception:
227
- logger.exception('Failed to upload log to S3')
228
- return
229
-
230
-
231
- def assign_uuid(history: list[tuple[str, str]], uuid_list: list[tuple[str, str]]) -> list[tuple[str, str]]:
232
- len_history = len(history)
233
- len_uuid_list = len(uuid_list)
234
- new_uuid_list = [x for x in uuid_list]
235
-
236
- if len_history > len_uuid_list:
237
- for t_history in history[len_uuid_list:]:
238
- if t_history[1] == '':
239
- # 入力だけされてるタイミング
240
- new_uuid_list.append((str(uuid.uuid4()), ''))
241
- else:
242
- # undoなどを経て、入力だけされてるタイミングを飛び越えた場合
243
- new_uuid_list.append((str(uuid.uuid4()), str(uuid.uuid4())))
244
- elif len_history < len_uuid_list:
245
- new_uuid_list = new_uuid_list[:len_history]
246
- elif len_history == len_uuid_list:
247
- for t_history, t_uuid in zip(history, uuid_list):
248
- if (t_history[1] != '') and (t_uuid[1] == ''):
249
- new_uuid_list.pop()
250
- new_uuid_list.append((t_uuid[0], str(uuid.uuid4())))
251
- elif (t_history[1] == '') and (t_uuid[1] != ''):
252
- new_uuid_list.pop()
253
- new_uuid_list.append((t_uuid[0], ''))
254
- return new_uuid_list
255
-
256
-
257
- with gr.Blocks(css='style.css') as demo:
258
- gr.Markdown(TITLE)
259
-
260
- with gr.Row():
261
- gr.HTML(
262
- """
263
- <div id="logo">
264
- <img src='file/key_visual.png' width=1200 min-width=300></img>
265
- </div>
266
- """
267
- )
268
-
269
- with gr.Group():
270
- chatbot = gr.Chatbot(
271
- label='Chatbot',
272
- height=600,
273
- avatar_images=['person_face.png', 'llama_face.png'],
274
- )
275
- with gr.Column():
276
- textbox = gr.Textbox(
277
- container=False,
278
- show_label=False,
279
- placeholder='指示を入力してください。例: カレーとハンバーグを組み合わせた美味しい料理を3つ教えて',
280
- scale=10,
281
- lines=10,
282
- )
283
- submit_button = gr.Button(
284
- '以下の説明文・免責事項・データ利用に同意して送信', variant='primary', scale=1, min_width=0
285
- )
286
- gr.Markdown(
287
- '※ 繰り返しが発生する場合は、以下「詳細設定」の `repetition_penalty` を1.05〜1.20など調整すると上手くいく場合があります'
288
- )
289
- with gr.Row():
290
- retry_button = gr.Button('🔄 同じ入力でもう一度生成', variant='secondary')
291
- undo_button = gr.Button('↩️ ひとつ前の状態に戻る', variant='secondary')
292
- clear_button = gr.Button('🗑️ これまでの出力を消す', variant='secondary')
293
-
294
- saved_input = gr.State()
295
- uuid_list = gr.State([])
296
-
297
- with gr.Accordion(label='上の対話履歴をスクリーンショット用に整形', open=False):
298
- output_textbox = gr.Markdown()
299
-
300
- with gr.Accordion(label='詳細設定', open=False):
301
- system_prompt = gr.Textbox(label='システムプロンプト', value=DEFAULT_SYSTEM_PROMPT, lines=8)
302
- max_new_tokens = gr.Slider(
303
- label='最大出力トークン数',
304
- minimum=1,
305
- maximum=MAX_MAX_NEW_TOKENS,
306
- step=1,
307
- value=DEFAULT_MAX_NEW_TOKENS,
308
- )
309
- repetition_penalty = gr.Slider(
310
- label='Repetition penalty',
311
- minimum=1.0,
312
- maximum=10.0,
313
- step=0.1,
314
- value=1.0,
315
- )
316
- do_sample = gr.Checkbox(label='do_sample', value=False)
317
- temperature = gr.Slider(
318
- label='Temperature',
319
- minimum=0.1,
320
- maximum=4.0,
321
- step=0.1,
322
- value=1.0,
323
- )
324
- top_p = gr.Slider(
325
- label='Top-p (nucleus sampling)',
326
- minimum=0.05,
327
- maximum=1.0,
328
- step=0.05,
329
- value=0.95,
330
- )
331
- top_k = gr.Slider(
332
- label='Top-k',
333
- minimum=1,
334
- maximum=1000,
335
- step=1,
336
- value=50,
337
- )
338
-
339
- gr.Examples(
340
- examples=examples,
341
- inputs=textbox,
342
- outputs=[textbox, chatbot],
343
- fn=process_example,
344
- cache_examples=True,
345
- )
346
-
347
- gr.Markdown(DESCRIPTION)
348
-
349
- textbox.submit(
350
- fn=clear_and_save_textbox,
351
- inputs=textbox,
352
- outputs=[textbox, saved_input],
353
- api_name=False,
354
- queue=False,
355
- ).then(
356
- fn=check_input_token_length,
357
- inputs=[saved_input, chatbot, system_prompt],
358
- api_name=False,
359
- queue=False,
360
- ).success(
361
- fn=display_input,
362
- inputs=[saved_input, chatbot],
363
- outputs=chatbot,
364
- api_name=False,
365
- queue=False,
366
- ).then(
367
- fn=assign_uuid,
368
- inputs=[chatbot, uuid_list],
369
- outputs=uuid_list,
370
- ).then(
371
- fn=output_log,
372
- inputs=[chatbot, uuid_list],
373
- ).then(
374
- fn=generate,
375
- inputs=[
376
- saved_input,
377
- chatbot,
378
- system_prompt,
379
- max_new_tokens,
380
- temperature,
381
- top_p,
382
- top_k,
383
- do_sample,
384
- repetition_penalty,
385
- ],
386
- outputs=chatbot,
387
- api_name=False,
388
- ).then(
389
- fn=assign_uuid,
390
- inputs=[chatbot, uuid_list],
391
- outputs=uuid_list,
392
- ).then(
393
- fn=output_log,
394
- inputs=[chatbot, uuid_list],
395
- ).then(
396
- fn=convert_history_to_str,
397
- inputs=chatbot,
398
- outputs=output_textbox,
399
- )
400
-
401
- button_event_preprocess = (
402
- submit_button.click(
403
- fn=clear_and_save_textbox,
404
- inputs=textbox,
405
- outputs=[textbox, saved_input],
406
- api_name=False,
407
- queue=False,
408
- )
409
- .then(
410
- fn=check_input_token_length,
411
- inputs=[saved_input, chatbot, system_prompt],
412
- api_name=False,
413
- queue=False,
414
- )
415
- .success(
416
- fn=display_input,
417
- inputs=[saved_input, chatbot],
418
- outputs=chatbot,
419
- api_name=False,
420
- queue=False,
421
- )
422
- .then(
423
- fn=assign_uuid,
424
- inputs=[chatbot, uuid_list],
425
- outputs=uuid_list,
426
- )
427
- .then(
428
- fn=output_log,
429
- inputs=[chatbot, uuid_list],
430
- )
431
- .success(
432
- fn=generate,
433
- inputs=[
434
- saved_input,
435
- chatbot,
436
- system_prompt,
437
- max_new_tokens,
438
- temperature,
439
- top_p,
440
- top_k,
441
- do_sample,
442
- repetition_penalty,
443
- ],
444
- outputs=chatbot,
445
- api_name=False,
446
- )
447
- .then(
448
- fn=assign_uuid,
449
- inputs=[chatbot, uuid_list],
450
- outputs=uuid_list,
451
- )
452
- .then(
453
- fn=output_log,
454
- inputs=[chatbot, uuid_list],
455
- )
456
- .then(
457
- fn=convert_history_to_str,
458
- inputs=chatbot,
459
- outputs=output_textbox,
460
- )
461
- )
462
-
463
- retry_button.click(
464
- fn=delete_prev_fn,
465
- inputs=chatbot,
466
- outputs=[chatbot, saved_input],
467
- api_name=False,
468
- queue=False,
469
- ).then(
470
- fn=check_input_token_length,
471
- inputs=[saved_input, chatbot, system_prompt],
472
- api_name=False,
473
- queue=False,
474
- ).success(
475
- fn=display_input,
476
- inputs=[saved_input, chatbot],
477
- outputs=chatbot,
478
- api_name=False,
479
- queue=False,
480
- ).then(
481
- fn=assign_uuid,
482
- inputs=[chatbot, uuid_list],
483
- outputs=uuid_list,
484
- ).then(
485
- fn=output_log,
486
- inputs=[chatbot, uuid_list],
487
- ).then(
488
- fn=generate,
489
- inputs=[
490
- saved_input,
491
- chatbot,
492
- system_prompt,
493
- max_new_tokens,
494
- temperature,
495
- top_p,
496
- top_k,
497
- do_sample,
498
- repetition_penalty,
499
- ],
500
- outputs=chatbot,
501
- api_name=False,
502
- ).then(
503
- fn=assign_uuid,
504
- inputs=[chatbot, uuid_list],
505
- outputs=uuid_list,
506
- ).then(
507
- fn=output_log,
508
- inputs=[chatbot, uuid_list],
509
- ).then(
510
- fn=convert_history_to_str,
511
- inputs=chatbot,
512
- outputs=output_textbox,
513
- )
514
-
515
- undo_button.click(
516
- fn=delete_prev_fn,
517
- inputs=chatbot,
518
- outputs=[chatbot, saved_input],
519
- api_name=False,
520
- queue=False,
521
- ).then(
522
- fn=assign_uuid,
523
- inputs=[chatbot, uuid_list],
524
- outputs=uuid_list,
525
- ).then(
526
- fn=lambda x: x,
527
- inputs=saved_input,
528
- outputs=textbox,
529
- api_name=False,
530
- queue=False,
531
- ).then(
532
- fn=convert_history_to_str,
533
- inputs=chatbot,
534
- outputs=output_textbox,
535
- )
536
-
537
- clear_button.click(
538
- fn=lambda: ([], ''),
539
- outputs=[chatbot, saved_input],
540
- queue=False,
541
- api_name=False,
542
- ).then(
543
- fn=assign_uuid,
544
- inputs=[chatbot, uuid_list],
545
- outputs=uuid_list,
546
- ).then(
547
- fn=convert_history_to_str,
548
- inputs=chatbot,
549
- outputs=output_textbox,
550
- )
551
-
552
- demo.queue(max_size=5).launch(server_name='0.0.0.0')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
key_visual.png DELETED

Git LFS Details

  • SHA256: 2fc23f82aace1505eff17f129609e82304a3d2fafdd3a3c5975c84e483d3aaa3
  • Pointer size: 131 Bytes
  • Size of remote file: 277 kB
llama_face.png DELETED

Git LFS Details

  • SHA256: 931fb24e165d9c548f5ce1cb0f03dcbe4b2ecf2fe9163cd985dcd394e780122a
  • Pointer size: 130 Bytes
  • Size of remote file: 40.4 kB
model_vllm.py DELETED
@@ -1,115 +0,0 @@
1
- from typing import Iterator, AsyncGenerator
2
- import json
3
- import logging
4
-
5
- from transformers import AutoTokenizer
6
- from vllm.engine.arg_utils import AsyncEngineArgs
7
- from vllm.engine.async_llm_engine import AsyncLLMEngine
8
- from vllm.sampling_params import SamplingParams
9
- from vllm.utils import random_uuid
10
-
11
- logger = logging.getLogger(__name__)
12
-
13
-
14
- # Initialize the LLM Engine
15
- def init_engine():
16
- engine_args = AsyncEngineArgs(model=model_id, dtype='bfloat16', disable_log_requests=True, disable_log_stats=True)
17
- engine = AsyncLLMEngine.from_engine_args(engine_args)
18
-
19
- return engine
20
-
21
-
22
- model_id = 'elyza/ELYZA-japanese-Llama-2-13b-instruct'
23
- tokenizer = AutoTokenizer.from_pretrained(model_id)
24
- engine = init_engine()
25
-
26
-
27
- # Generator function for streaming response
28
- async def stream_results(prompt, sampling_params):
29
- global engine
30
- request_id = random_uuid()
31
- results_generator = engine.generate(prompt, sampling_params, request_id)
32
-
33
- async for request_output in results_generator:
34
- text_outputs = [output.text for output in request_output.outputs]
35
- yield text_outputs
36
-
37
-
38
- def get_prompt(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> str:
39
- texts = [f'<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n']
40
- # The first user input is _not_ stripped
41
- do_strip = False
42
- for user_input, response in chat_history:
43
- user_input = user_input.strip() if do_strip else user_input
44
- do_strip = True
45
- texts.append(f'{user_input} [/INST] {response.strip()} </s><s>[INST] ')
46
- message = message.strip() if do_strip else message
47
- texts.append(f'{message} [/INST]')
48
- return ''.join(texts)
49
-
50
-
51
- def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
52
- prompt = get_prompt(message, chat_history, system_prompt)
53
- input_ids = tokenizer([prompt], return_tensors='np', add_special_tokens=False)['input_ids']
54
- return input_ids.shape[-1]
55
-
56
-
57
- # Function to generate a response
58
- async def generate_response(engine, prompt: str):
59
- request_id = random_uuid()
60
- sampling_params = SamplingParams()
61
- results_generator = engine.generate(prompt, sampling_params, request_id)
62
-
63
- final_output = None
64
- async for request_output in results_generator:
65
- final_output = request_output
66
-
67
- assert final_output is not None
68
- text_outputs = [output.text for output in final_output.outputs]
69
- return text_outputs
70
-
71
-
72
- async def run(
73
- message: str,
74
- chat_history: list[tuple[str, str]],
75
- system_prompt: str,
76
- max_new_tokens: int = 1024,
77
- temperature: float = 0.8,
78
- top_p: float = 0.95,
79
- top_k: int = 50,
80
- do_sample: bool = False,
81
- repetition_penalty: float = 1.2,
82
- stream: bool = False,
83
- ) -> AsyncGenerator | str:
84
- request_id = random_uuid()
85
- prompt = get_prompt(message=message, chat_history=chat_history, system_prompt=system_prompt)
86
-
87
- if not do_sample:
88
- # greedy
89
- temperature = 0
90
- sampling_params = SamplingParams(
91
- max_tokens=max_new_tokens,
92
- temperature=temperature,
93
- top_p=top_p,
94
- top_k=top_k,
95
- repetition_penalty=repetition_penalty,
96
- )
97
-
98
- logger.info(f'queue: {request_id}')
99
- results_generator = engine.generate(
100
- prompt=prompt,
101
- sampling_params=sampling_params,
102
- request_id=request_id,
103
- )
104
-
105
- # Streaming case
106
- async def stream_results() -> AsyncGenerator:
107
- async for request_output in results_generator:
108
- yield ''.join([output.text for output in request_output.outputs])
109
-
110
- if stream:
111
- return stream_results()
112
- else:
113
- async for request_output in results_generator:
114
- pass
115
- return ''.join([output.text for output in request_output.outputs])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
person_face.png DELETED

Git LFS Details

  • SHA256: 9f34d5973013ce64fbf912fd6afe0f54f3dad436d5ad1edd8e3047e67dda117a
  • Pointer size: 131 Bytes
  • Size of remote file: 224 kB
requirements.txt DELETED
@@ -1,153 +0,0 @@
1
- accelerate==0.25.0
2
- aiofiles==23.2.1
3
- aiohttp==3.9.1
4
- aioprometheus==23.3.0
5
- aiosignal==1.3.1
6
- altair==5.2.0
7
- anyio==3.7.1
8
- asttokens==2.4.1
9
- attrs==23.1.0
10
- auto-gptq==0.6.0
11
- bitsandbytes==0.41.3.post2
12
- boto3==1.34.7
13
- botocore==1.34.7
14
- certifi==2023.11.17
15
- charset-normalizer==3.3.2
16
- click==8.1.7
17
- colorama==0.4.6
18
- coloredlogs==15.0.1
19
- comm==0.2.0
20
- contourpy==1.2.0
21
- coverage==7.3.4
22
- cycler==0.12.1
23
- datasets==2.14.4
24
- debugpy==1.8.0
25
- decorator==5.1.1
26
- dill==0.3.7
27
- distlib==0.3.8
28
- executing==2.0.1
29
- fastapi==0.105.0
30
- ffmpy==0.3.1
31
- filelock==3.13.1
32
- fonttools==4.47.0
33
- frozenlist==1.4.1
34
- fsspec==2023.12.2
35
- gekko==1.0.6
36
- gradio==3.50.2
37
- gradio_client==0.6.1
38
- h11==0.14.0
39
- httpcore==1.0.2
40
- httptools==0.6.1
41
- httpx==0.26.0
42
- huggingface-hub==0.20.1
43
- humanfriendly==10.0
44
- idna==3.6
45
- importlib-resources==6.1.1
46
- iniconfig==2.0.0
47
- ipykernel==6.27.1
48
- ipython==8.19.0
49
- isort==5.13.2
50
- jedi==0.19.1
51
- Jinja2==3.1.2
52
- jmespath==1.0.1
53
- jsonschema==4.20.0
54
- jsonschema-specifications==2023.11.2
55
- jupyter_client==8.6.0
56
- jupyter_core==5.5.1
57
- kiwisolver==1.4.5
58
- MarkupSafe==2.1.3
59
- matplotlib==3.8.2
60
- matplotlib-inline==0.1.6
61
- mpmath==1.3.0
62
- msgpack==1.0.7
63
- multidict==6.0.4
64
- multiprocess==0.70.15
65
- mypy==1.8.0
66
- mypy-extensions==1.0.0
67
- nest-asyncio==1.5.8
68
- networkx==3.2.1
69
- ninja==1.11.1.1
70
- numpy==1.26.2
71
- nvidia-cublas-cu12==12.1.3.1
72
- nvidia-cuda-cupti-cu12==12.1.105
73
- nvidia-cuda-nvrtc-cu12==12.1.105
74
- nvidia-cuda-runtime-cu12==12.1.105
75
- nvidia-cudnn-cu12==8.9.2.26
76
- nvidia-cufft-cu12==11.0.2.54
77
- nvidia-curand-cu12==10.3.2.106
78
- nvidia-cusolver-cu12==11.4.5.107
79
- nvidia-cusparse-cu12==12.1.0.106
80
- nvidia-nccl-cu12==2.18.1
81
- nvidia-nvjitlink-cu12==12.3.101
82
- nvidia-nvtx-cu12==12.1.105
83
- optimum==1.16.1
84
- orjson==3.9.10
85
- packaging==23.2
86
- pandas==2.1.4
87
- parso==0.8.3
88
- peft==0.7.1
89
- pexpect==4.9.0
90
- Pillow==10.1.0
91
- platformdirs==4.1.0
92
- pluggy==1.3.0
93
- prompt-toolkit==3.0.43
94
- protobuf==4.25.1
95
- psutil==5.9.7
96
- ptyprocess==0.7.0
97
- pure-eval==0.2.2
98
- py==1.11.0
99
- pyarrow==14.0.2
100
- pydantic==1.10.13
101
- pydub==0.25.1
102
- Pygments==2.17.2
103
- pyparsing==3.1.1
104
- pytest==7.4.3
105
- pytest-cov==2.12.1
106
- pytest-mock==3.12.0
107
- pytest-mypy==0.9.1
108
- python-dateutil==2.8.2
109
- python-dotenv==1.0.0
110
- python-multipart==0.0.6
111
- pytz==2023.3.post1
112
- PyYAML==6.0.1
113
- pyzmq==25.1.2
114
- quantile-python==1.1
115
- ray==2.9.0
116
- referencing==0.32.0
117
- regex==2023.10.3
118
- requests==2.31.0
119
- rouge==1.0.1
120
- rpds-py==0.15.2
121
- ruff==0.1.9
122
- s3transfer==0.10.0
123
- safetensors==0.4.1
124
- semantic-version==2.10.0
125
- sentencepiece==0.1.99
126
- six==1.16.0
127
- sniffio==1.3.0
128
- stack-data==0.6.3
129
- starlette==0.27.0
130
- sympy==1.12
131
- tokenizers==0.15.0
132
- toml==0.10.2
133
- toolz==0.12.0
134
- torch==2.1.2
135
- tornado==6.4
136
- tox==3.28.0
137
- tqdm==4.66.1
138
- traitlets==5.14.0
139
- transformers==4.36.2
140
- triton==2.1.0
141
- typing_extensions==4.9.0
142
- tzdata==2023.3
143
- urllib3==2.0.7
144
- uvicorn==0.25.0
145
- uvloop==0.19.0
146
- virtualenv==20.25.0
147
- vllm==0.2.6
148
- watchfiles==0.21.0
149
- wcwidth==0.2.12
150
- websockets==11.0.3
151
- xformers==0.0.23.post1
152
- xxhash==3.4.1
153
- yarl==1.9.4