e-mon commited on
Commit
192cff8
1 Parent(s): 209b7e9

delete files

Browse files
Files changed (8) hide show
  1. LICENSE.txt +0 -126
  2. USE_POLICY.md +0 -50
  3. app.py +0 -549
  4. key_visual.png +0 -3
  5. llama_face.png +0 -0
  6. model.py +0 -77
  7. person_face.png +0 -0
  8. requirements.txt +0 -10
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,549 +0,0 @@
1
- from datetime import datetime, timezone, timedelta
2
- import os
3
- import time
4
- from typing import Iterator
5
- import uuid
6
-
7
- import boto3
8
- from botocore.config import Config
9
- import gradio as gr
10
- import pandas as pd
11
- import torch
12
-
13
- from model import get_input_token_length, run
14
-
15
- JST = timezone(timedelta(hours=+9), "JST")
16
-
17
- DEFAULT_SYSTEM_PROMPT = "あなたは誠実で優秀な日本人のアシスタントです。"
18
- MAX_MAX_NEW_TOKENS = 2048
19
- DEFAULT_MAX_NEW_TOKENS = 512
20
- MAX_INPUT_TOKEN_LENGTH = 4000
21
-
22
- TITLE = "# ELYZA-japanese-CodeLlama-7b-instruct-demo"
23
- DESCRIPTION = """
24
- ## 概要
25
- - [ELYZA-japanese-CodeLlama-7b](https://huggingface.co/elyza/ELYZA-japanese-CodeLlama-7b)は、[株式会社ELYZA](https://elyza.ai/) (以降「当社」と呼称) が[Code Llama](https://ai.meta.com/research/publications/code-llama-open-foundation-models-for-code/)をベースとして日本語能力を拡張するために事前学習を行ったモデルです。
26
- - [ELYZA-japanese-CodeLlama-7b-instruct](https://huggingface.co/elyza/ELYZA-japanese-CodeLlama-7b-instruct)は[ELYZA-japanese-CodeLlama-7b](ttps://huggingface.co/elyza/ELYZA-japanese-CodeLlama-7b)を弊社独自のinstruction tuning用データセットで事後学習したモデルです。
27
- - 本デモではこのモデルが使われています。
28
- - 詳細は[Blog記事](https://zenn.dev/elyza/articles/fcbf103e0a05b1)を参照してください。
29
- - 本デモではこちらの[Llama-2 7B Chat](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat)のデモをベースにさせていただきました。
30
-
31
- ## License
32
- - Code Llama is licensed under the LLAMA 2 Community License, Copyright (c) Meta Platforms, Inc. All Rights Reserved.
33
-
34
- ## 免責事項
35
- - 当社は、本デモについて、ユーザーの特定の目的に適合すること、期待する機能・正確性・有用性を有すること、出力データが完全性、正確性、有用性を有すること、ユーザーによる本サービスの利用がユーザーに適用のある法令等に適合すること、継続的に利用できること、及び不具合が生じないことについて、明示又は黙示を問わず何ら保証するものではありません。
36
- - 当社は、本デモに関してユーザーが被った損害等につき、一切の責任を負わないものとし、ユーザーはあらかじめこれを承諾するものとします。
37
- - 当社は、本デモを通じて、ユーザー又は第三者の個人情報を取得することを想定しておらず、ユーザーは、本デモに、ユーザー又は第三者の氏名その他の特定の個人を識別することができる情報等を入力等してはならないものとします。
38
- - ユーザーは、当社が本デモ又は本デモに使用されているアルゴリズム等の改善・向上に使用することを許諾するものとします。
39
-
40
- ## 本デモで入力・出力されたデータの記録・利用に関して
41
- - 本デモで入力・出力されたデータは当社にて記録させていただき、今後の本デモ又は本デモに使用されているアルゴリズム等の改善・向上に使用させていただく場合がございます。
42
-
43
- ## We are hiring!
44
- - 当社 (株式会社ELYZA) に興味のある方、ぜひお話ししませんか?
45
- - 機械学習エンジニア・インターン募集: https://open.talentio.com/r/1/c/elyza/homes/2507
46
- - カジュアル面談はこちら: https://chillout.elyza.ai/elyza-japanese-llama2-7b
47
- """
48
-
49
- EXAMPLES = [
50
- '''
51
- エラトステネスの篩についてサンプルコードを示し、解説してください。
52
- '''.strip(),
53
- '''
54
- モンテカルロ法で円周率を求めるコードをTypeScriptで書いてください。
55
- '''.strip(),
56
- '''
57
- D3.jsで、データの数だけ丸を横に並べて、それぞれにカーソルを合わせると「それが左から何番目の丸か (1始まり)」を表示するようなコードを書いて
58
- '''.strip(),
59
- '''
60
- 以下はUnionFindのPython実装です。このコードに対し、ユニットテストのコードを書いてください
61
-
62
- ```
63
- class UnionFind:
64
- def __init__(self, N):
65
- self.rank = [0]*N
66
- self.par = list(range(N))
67
-
68
- def find(self, x):
69
- if x != self.par[x]:
70
- self.par[x] = self.find(self.par[x])
71
- return self.par[x]
72
-
73
- def unite(self, x, y):
74
- x, y = self.find(x), self.find(y)
75
- if(self.rank[x] > self.rank[y]):
76
- self.par[y] = x
77
- else:
78
- self.par[x] = y
79
- if(self.rank[x] == self.rank[y]):
80
- self.rank[y] += 1
81
- ```
82
- '''.strip()
83
- ]
84
-
85
- if not torch.cuda.is_available():
86
- DESCRIPTION += '\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>'
87
-
88
- s3 = boto3.client(
89
- "s3",
90
- aws_access_key_id=os.environ["AWS_ACCESS_KEY_ID"],
91
- aws_secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"],
92
- region_name=os.environ["S3_REGION"],
93
- config=Config(
94
- connect_timeout=5,
95
- read_timeout=5,
96
- retries={
97
- "mode": "standard",
98
- "total_max_attempts": 3,
99
- }
100
- )
101
- )
102
-
103
- def clear_and_save_textbox(message: str) -> tuple[str, str]:
104
- return '', message
105
-
106
-
107
- def display_input(message: str,
108
- history: list[tuple[str, str]]) -> list[tuple[str, str]]:
109
- history.append((message, ''))
110
- return history
111
-
112
-
113
- def delete_prev_fn(
114
- history: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], str]:
115
- try:
116
- message, _ = history.pop()
117
- except IndexError:
118
- message = ''
119
- return history, message or ''
120
-
121
-
122
- def generate(
123
- message: str,
124
- history_with_input: list[tuple[str, str]],
125
- system_prompt: str,
126
- max_new_tokens: int,
127
- temperature: float,
128
- top_p: float,
129
- top_k: int,
130
- do_sample: bool,
131
- repetition_penalty: float,
132
- ) -> Iterator[list[tuple[str, str]]]:
133
- if max_new_tokens > MAX_MAX_NEW_TOKENS:
134
- raise ValueError
135
-
136
- history = history_with_input[:-1]
137
- generator = run(
138
- message,
139
- history,
140
- system_prompt,
141
- max_new_tokens,
142
- float(temperature),
143
- float(top_p),
144
- top_k,
145
- do_sample,
146
- float(repetition_penalty),
147
- )
148
- try:
149
- first_response = next(generator)
150
- yield history + [(message, first_response)]
151
- except StopIteration:
152
- yield history + [(message, '')]
153
- for response in generator:
154
- yield history + [(message, response)]
155
-
156
-
157
- def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
158
- generator = generate(
159
- message=message,
160
- history_with_input=[],
161
- system_prompt=DEFAULT_SYSTEM_PROMPT,
162
- max_new_tokens=DEFAULT_MAX_NEW_TOKENS,
163
- temperature=1,
164
- top_p=0.95,
165
- top_k=50,
166
- do_sample=False,
167
- repetition_penalty=1.0,
168
- )
169
- for x in generator:
170
- pass
171
- return '', x
172
-
173
-
174
- def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
175
- input_token_length = get_input_token_length(message, chat_history, system_prompt)
176
- if input_token_length > MAX_INPUT_TOKEN_LENGTH:
177
- raise gr.Error(
178
- f"合計対話長が長すぎます ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH})。入力文章を短くするか、「🗑️ これまでの出力を消す」ボタンを押してから再実行してください。"
179
- )
180
-
181
- if len(message) <= 0:
182
- raise gr.Error("入力が空です。1文字以上の文字列を入力してください。")
183
-
184
-
185
- def convert_history_to_str(history: list[tuple[str, str]]) -> str:
186
- res = []
187
- for user_utt, sys_utt in history:
188
- res.append(f"😃: {user_utt}")
189
- res.append(f"🤖: {sys_utt}")
190
- return "<br>".join(res)
191
-
192
-
193
- def output_log(history: list[tuple[str, str]], uuid_list: list[tuple[str, str]]) -> None:
194
- tree_uuid = uuid_list[0][0]
195
- last_messages = history[-1]
196
- last_uuids = uuid_list[-1]
197
- parent_uuid = None
198
- record_message = None
199
- record_uuid = None
200
- role = None
201
- if last_uuids[1] == '':
202
- role = "user"
203
- record_message = last_messages[0]
204
- record_uuid = last_uuids[0]
205
- if len(history) >= 2:
206
- parent_uuid = uuid_list[-2][1]
207
- else:
208
- parent_uuid = last_uuids[0]
209
- else:
210
- role = "assistant"
211
- record_message = last_messages[1]
212
- record_uuid = last_uuids[1]
213
- parent_uuid = last_uuids[0]
214
-
215
- now = datetime.fromtimestamp(time.time(), JST)
216
- yyyymmdd = now.strftime('%Y%m%d')
217
- created_at = now.strftime("%Y-%m-%d %H:%M:%S.%f")
218
-
219
- d = {
220
- "created_at": created_at,
221
- "tree_uuid": tree_uuid,
222
- "parent_uuid": parent_uuid,
223
- "uuid": record_uuid,
224
- "role": role,
225
- "message": record_message,
226
- }
227
- try:
228
- csv_buffer = pd.DataFrame(d, index=[0]).to_csv(index=None)
229
- s3.put_object(
230
- Bucket=os.environ["S3_BUCKET"],
231
- Key=f"{os.environ['S3_KEY_PREFIX']}/{yyyymmdd}/{record_uuid}.csv",
232
- Body=csv_buffer
233
- )
234
- except:
235
- pass
236
- return
237
-
238
-
239
- def assign_uuid(history: list[tuple[str, str]], uuid_list: list[tuple[str, str]]) -> list[tuple[str, str]]:
240
- len_history = len(history)
241
- len_uuid_list = len(uuid_list)
242
- new_uuid_list = [x for x in uuid_list]
243
-
244
- if len_history > len_uuid_list:
245
- for t_history in history[len_uuid_list:]:
246
- if t_history[1] == "":
247
- # 入力だけされてるタイミング
248
- new_uuid_list.append((str(uuid.uuid4()), ""))
249
- else:
250
- # undoなどを経て、入力だけされてるタイミングを飛び越えた場合
251
- new_uuid_list.append((str(uuid.uuid4()), str(uuid.uuid4())))
252
- elif len_history < len_uuid_list:
253
- new_uuid_list = new_uuid_list[:len_history]
254
- elif len_history == len_uuid_list:
255
- for t_history, t_uuid in zip(history, uuid_list):
256
- if (t_history[1] != "") and (t_uuid[1] == ""):
257
- new_uuid_list.pop()
258
- new_uuid_list.append((t_uuid[0], str(uuid.uuid4())))
259
- elif (t_history[1] == "") and (t_uuid[1] != ""):
260
- new_uuid_list.pop()
261
- new_uuid_list.append((t_uuid[0], ""))
262
- return new_uuid_list
263
-
264
-
265
- with gr.Blocks(css='style.css') as demo:
266
- gr.Markdown(TITLE)
267
-
268
- with gr.Row():
269
- gr.HTML('''
270
- <div id="logo">
271
- <img src='file/key_visual.png' width=1200 min-width=300></img>
272
- </div>
273
- ''')
274
-
275
- with gr.Group():
276
- chatbot = gr.Chatbot(
277
- label='Chatbot',
278
- height=600,
279
- avatar_images=["person_face.png", "llama_face.png"],
280
- )
281
- with gr.Column():
282
- textbox = gr.Textbox(
283
- container=False,
284
- show_label=False,
285
- placeholder='ディレクトリ `/home/llama/data` 以下のCSVファイルをすべて読み込んでpandasのDataFrameにしてから、それらを結合して',
286
- scale=10,
287
- lines=10,
288
- )
289
- submit_button = gr.Button('以下の説明文・免責事項・データ利用に同意して送信',
290
- variant='primary',
291
- scale=1,
292
- min_width=0)
293
- gr.Markdown("※ 繰り返しが発生する場合は、以下「詳細設定」の `repetition_penalty` を1.05〜1.20など調整すると上手くいく場合があります")
294
- with gr.Row():
295
- retry_button = gr.Button('🔄 同じ入力でもう一度生成', variant='secondary')
296
- undo_button = gr.Button('↩️ ひとつ前の状態に戻る', variant='secondary')
297
- clear_button = gr.Button('🗑️ これまでの出力を消す', variant='secondary')
298
-
299
- saved_input = gr.State()
300
- uuid_list = gr.State([])
301
-
302
- with gr.Accordion(label='上の対話履歴をスクリーンショット用に整形', open=False):
303
- output_textbox = gr.Markdown()
304
-
305
- with gr.Accordion(label='詳細設定', open=False):
306
- system_prompt = gr.Textbox(label='システムプロンプト',
307
- value=DEFAULT_SYSTEM_PROMPT,
308
- lines=8)
309
- max_new_tokens = gr.Slider(
310
- label='最大出力トークン数',
311
- minimum=1,
312
- maximum=MAX_MAX_NEW_TOKENS,
313
- step=1,
314
- value=DEFAULT_MAX_NEW_TOKENS,
315
- )
316
- repetition_penalty = gr.Slider(
317
- label='Repetition penalty',
318
- minimum=1.0,
319
- maximum=10.0,
320
- step=0.1,
321
- value=1.0,
322
- )
323
- do_sample = gr.Checkbox(label='do_sample', value=False)
324
- temperature = gr.Slider(
325
- label='Temperature',
326
- minimum=0.1,
327
- maximum=4.0,
328
- step=0.1,
329
- value=1.0,
330
- )
331
- top_p = gr.Slider(
332
- label='Top-p (nucleus sampling)',
333
- minimum=0.05,
334
- maximum=1.0,
335
- step=0.05,
336
- value=0.95,
337
- )
338
- top_k = gr.Slider(
339
- label='Top-k',
340
- minimum=1,
341
- maximum=1000,
342
- step=1,
343
- value=50,
344
- )
345
-
346
- gr.Examples(
347
- examples=EXAMPLES,
348
- inputs=textbox,
349
- outputs=[textbox, chatbot],
350
- fn=process_example,
351
- cache_examples=True,
352
- )
353
-
354
- gr.Markdown(DESCRIPTION)
355
-
356
- textbox.submit(
357
- fn=clear_and_save_textbox,
358
- inputs=textbox,
359
- outputs=[textbox, saved_input],
360
- api_name=False,
361
- queue=False,
362
- ).then(
363
- fn=check_input_token_length,
364
- inputs=[saved_input, chatbot, system_prompt],
365
- api_name=False,
366
- queue=False,
367
- ).success(
368
- fn=display_input,
369
- inputs=[saved_input, chatbot],
370
- outputs=chatbot,
371
- api_name=False,
372
- queue=False,
373
- ).then(
374
- fn=assign_uuid,
375
- inputs=[chatbot, uuid_list],
376
- outputs=uuid_list,
377
- ).then(
378
- fn=output_log,
379
- inputs=[chatbot, uuid_list],
380
- ).then(
381
- fn=generate,
382
- inputs=[
383
- saved_input,
384
- chatbot,
385
- system_prompt,
386
- max_new_tokens,
387
- temperature,
388
- top_p,
389
- top_k,
390
- do_sample,
391
- repetition_penalty,
392
- ],
393
- outputs=chatbot,
394
- api_name=False,
395
- ).then(
396
- fn=assign_uuid,
397
- inputs=[chatbot, uuid_list],
398
- outputs=uuid_list,
399
- ).then(
400
- fn=output_log,
401
- inputs=[chatbot, uuid_list],
402
- ).then(
403
- fn=convert_history_to_str,
404
- inputs=chatbot,
405
- outputs=output_textbox,
406
- )
407
-
408
- button_event_preprocess = submit_button.click(
409
- fn=clear_and_save_textbox,
410
- inputs=textbox,
411
- outputs=[textbox, saved_input],
412
- api_name=False,
413
- queue=False,
414
- ).then(
415
- fn=check_input_token_length,
416
- inputs=[saved_input, chatbot, system_prompt],
417
- api_name=False,
418
- queue=False,
419
- ).success(
420
- fn=display_input,
421
- inputs=[saved_input, chatbot],
422
- outputs=chatbot,
423
- api_name=False,
424
- queue=False,
425
- ).then(
426
- fn=assign_uuid,
427
- inputs=[chatbot, uuid_list],
428
- outputs=uuid_list,
429
- ).then(
430
- fn=output_log,
431
- inputs=[chatbot, uuid_list],
432
- ).success(
433
- fn=generate,
434
- inputs=[
435
- saved_input,
436
- chatbot,
437
- system_prompt,
438
- max_new_tokens,
439
- temperature,
440
- top_p,
441
- top_k,
442
- do_sample,
443
- repetition_penalty,
444
- ],
445
- outputs=chatbot,
446
- api_name=False,
447
- ).then(
448
- fn=assign_uuid,
449
- inputs=[chatbot, uuid_list],
450
- outputs=uuid_list,
451
- ).then(
452
- fn=output_log,
453
- inputs=[chatbot, uuid_list],
454
- ).then(
455
- fn=convert_history_to_str,
456
- inputs=chatbot,
457
- outputs=output_textbox,
458
- )
459
-
460
- retry_button.click(
461
- fn=delete_prev_fn,
462
- inputs=chatbot,
463
- outputs=[chatbot, saved_input],
464
- api_name=False,
465
- queue=False,
466
- ).then(
467
- fn=check_input_token_length,
468
- inputs=[saved_input, chatbot, system_prompt],
469
- api_name=False,
470
- queue=False,
471
- ).success(
472
- fn=display_input,
473
- inputs=[saved_input, chatbot],
474
- outputs=chatbot,
475
- api_name=False,
476
- queue=False,
477
- ).then(
478
- fn=assign_uuid,
479
- inputs=[chatbot, uuid_list],
480
- outputs=uuid_list,
481
- ).then(
482
- fn=output_log,
483
- inputs=[chatbot, uuid_list],
484
- ).then(
485
- fn=generate,
486
- inputs=[
487
- saved_input,
488
- chatbot,
489
- system_prompt,
490
- max_new_tokens,
491
- temperature,
492
- top_p,
493
- top_k,
494
- do_sample,
495
- repetition_penalty,
496
- ],
497
- outputs=chatbot,
498
- api_name=False,
499
- ).then(
500
- fn=assign_uuid,
501
- inputs=[chatbot, uuid_list],
502
- outputs=uuid_list,
503
- ).then(
504
- fn=output_log,
505
- inputs=[chatbot, uuid_list],
506
- ).then(
507
- fn=convert_history_to_str,
508
- inputs=chatbot,
509
- outputs=output_textbox,
510
- )
511
-
512
- undo_button.click(
513
- fn=delete_prev_fn,
514
- inputs=chatbot,
515
- outputs=[chatbot, saved_input],
516
- api_name=False,
517
- queue=False,
518
- ).then(
519
- fn=assign_uuid,
520
- inputs=[chatbot, uuid_list],
521
- outputs=uuid_list,
522
- ).then(
523
- fn=lambda x: x,
524
- inputs=saved_input,
525
- outputs=textbox,
526
- api_name=False,
527
- queue=False,
528
- ).then(
529
- fn=convert_history_to_str,
530
- inputs=chatbot,
531
- outputs=output_textbox,
532
- )
533
-
534
- clear_button.click(
535
- fn=lambda: ([], ''),
536
- outputs=[chatbot, saved_input],
537
- queue=False,
538
- api_name=False,
539
- ).then(
540
- fn=assign_uuid,
541
- inputs=[chatbot, uuid_list],
542
- outputs=uuid_list,
543
- ).then(
544
- fn=convert_history_to_str,
545
- inputs=chatbot,
546
- outputs=output_textbox,
547
- )
548
-
549
- demo.queue(max_size=5).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
key_visual.png DELETED

Git LFS Details

  • SHA256: c9d40b4a5a484dbc5506a702e01e2c1a4284343b9dfb15fc022fbe3b84f090d9
  • Pointer size: 132 Bytes
  • Size of remote file: 1.57 MB
llama_face.png DELETED
Binary file (106 kB)
 
model.py DELETED
@@ -1,77 +0,0 @@
1
- import logging
2
- from threading import Thread
3
- from typing import Iterator
4
-
5
- import torch
6
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
7
-
8
- model_id = 'elyza/ELYZA-japanese-CodeLlama-7b-instruct'
9
- if torch.cuda.is_available():
10
- model = AutoModelForCausalLM.from_pretrained(
11
- model_id,
12
- torch_dtype=torch.bfloat16,
13
- device_map='auto',
14
- use_auth_token=True,
15
- use_cache=True,
16
- )
17
- else:
18
- model = None
19
- tokenizer = AutoTokenizer.from_pretrained(model_id)
20
-
21
-
22
- def get_prompt(message: str, chat_history: list[tuple[str, str]],
23
- system_prompt: str) -> str:
24
- texts = [f'<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n']
25
- # The first user input is _not_ stripped
26
- do_strip = False
27
- for user_input, response in chat_history:
28
- user_input = user_input.strip() if do_strip else user_input
29
- do_strip = True
30
- texts.append(f'{user_input} [/INST] {response.strip()} </s><s>[INST] ')
31
- message = message.strip() if do_strip else message
32
- texts.append(f'{message} [/INST]')
33
- return ''.join(texts)
34
-
35
-
36
- def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
37
- prompt = get_prompt(message, chat_history, system_prompt)
38
- input_ids = tokenizer([prompt], return_tensors='np', add_special_tokens=False)['input_ids']
39
- return input_ids.shape[-1]
40
-
41
-
42
- def run(message: str,
43
- chat_history: list[tuple[str, str]],
44
- system_prompt: str,
45
- max_new_tokens: int = 1024,
46
- temperature: float = 0.8,
47
- top_p: float = 0.95,
48
- top_k: int = 50,
49
- do_sample: bool = False,
50
- repetition_penalty: float = 1.2) -> Iterator[str]:
51
- prompt = get_prompt(message, chat_history, system_prompt)
52
- inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda')
53
-
54
- streamer = TextIteratorStreamer(tokenizer,
55
- timeout=10.,
56
- skip_prompt=True,
57
- skip_special_tokens=True)
58
- generate_kwargs = dict(
59
- inputs,
60
- streamer=streamer,
61
- max_new_tokens=max_new_tokens,
62
- do_sample=do_sample,
63
- top_p=top_p,
64
- top_k=top_k,
65
- temperature=temperature,
66
- num_beams=1,
67
- repetition_penalty=repetition_penalty,
68
- pad_token_id=tokenizer.eos_token_id,
69
- eos_token_id=tokenizer.eos_token_id,
70
- )
71
- t = Thread(target=model.generate, kwargs=generate_kwargs)
72
- t.start()
73
-
74
- outputs = []
75
- for text in streamer:
76
- outputs.append(text)
77
- yield ''.join(outputs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
person_face.png DELETED
Binary file (224 kB)
 
requirements.txt DELETED
@@ -1,10 +0,0 @@
1
- accelerate==0.24.1
2
- bitsandbytes==0.40.2
3
- gradio==3.41.0
4
- protobuf==3.20.3
5
- scipy==1.11.1
6
- sentencepiece==0.1.99
7
- torch==2.0.1
8
- transformers==4.35.0
9
- boto3==1.28.35
10
- pandas==2.0.3