nengrenjie83 commited on
Commit
c44a4fe
1 Parent(s): d90912e

Upload 10 files

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