kkawamu1 commited on
Commit
3e2a57b
·
0 Parent(s):

Upload codes

Browse files
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
.streamlit/config.toml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [theme]
2
+ base="light"
LICENSE ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
README.md ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Huggingface Multi Inference Rank Eval
3
+ emoji: 🤔
4
+ colorFrom: yellow
5
+ colorTo: purple
6
+ sdk: streamlit
7
+ sdk_version: 1.10.0
8
+ app_file: ./app/main_page.py
9
+ pinned: false
10
+ license: cc
11
+ ---
12
+
13
+ # huggingface_multi_inference_rank_eval
14
+ **This app lets the users play around with Huggingface models on a prommpted multiple choice QA inference.**
15
+
16
+ Recenet researches like [GPT-3](https://arxiv.org/abs/2005.14165), [FLAN](https://arxiv.org/abs/2109.01652), and [T0](https://arxiv.org/abs/2110.08207) showed a promising direction in zero-shot generalization via prompting. Rathern than pretraining on a huge dataset and finetuning a model on downstream task, we can directly ask a question to a model by prompting a model on a task!
17
+
18
+
19
+ <p align="center">
20
+ <img src="assets/demo.png" width="800"/>
21
+ </p>
22
+
23
+ This app lets users interact with various models hosted on [Huggingface models](https://huggingface.co/models) and ask a multiple choice question. Models rank the choices with their log probabilities and pick the choice with highest log probability. We currently supoort [CausalLM](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoModelForCausalLM) and [Seq2SeqLM](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoModelForSeq2SeqLM).
24
+
25
+ e.g.
26
+ ```
27
+ Question: Huggingface is awesome. True or False?
28
+ Answer choices: True, False
29
+ Prediction: True
30
+ ```
31
+
32
+ **You can access the [hosted version](https://huggingface.co/spaces/kkawamu1/huggingface_multi_inference_rank_eval).**
33
+
34
+ ## Setup
35
+ Clone the repository, install the required packages and run:
36
+ ```bash
37
+ streamlit run ./app/main_page.py
38
+ ```
39
+
40
+
41
+ ## Reference
42
+ A chunk of codes used for this projects is taken and insipred from the following works and their related repository:
43
+ ```bibtex
44
+ @inproceedings{sanh2022multitask,
45
+ title={Multitask Prompted Training Enables Zero-Shot Task Generalization},
46
+ author={Victor Sanh and Albert Webson and Colin Raffel and Stephen Bach and Lintang Sutawika and Zaid Alyafeai and Antoine Chaffin and Arnaud Stiegler and Arun Raja and Manan Dey and M Saiful Bari and Canwen Xu and Urmish Thakker and Shanya Sharma Sharma and Eliza Szczechla and Taewoon Kim and Gunjan Chhablani and Nihal Nayak and Debajyoti Datta and Jonathan Chang and Mike Tian-Jian Jiang and Han Wang and Matteo Manica and Sheng Shen and Zheng Xin Yong and Harshit Pandey and Rachel Bawden and Thomas Wang and Trishala Neeraj and Jos Rozen and Abheesht Sharma and Andrea Santilli and Thibault Fevry and Jason Alan Fries and Ryan Teehan and Teven Le Scao and Stella Biderman and Leo Gao and Thomas Wolf and Alexander M Rush},
47
+ booktitle={International Conference on Learning Representations},
48
+ year={2022}
49
+ url={https://openreview.net/forum?id=9Vrb9D0WI4}
50
+ ```
51
+ ```bibtex
52
+ @software{eval-harness,
53
+ author = {Gao, Leo and
54
+ Tow, Jonathan and
55
+ Biderman, Stella and
56
+ Black, Sid and
57
+ DiPofi, Anthony and
58
+ Foster, Charles and
59
+ Golding, Laurence and
60
+ Hsu, Jeffrey and
61
+ McDonell, Kyle and
62
+ Muennighoff, Niklas and
63
+ Phang, Jason and
64
+ Reynolds, Laria and
65
+ Tang, Eric and
66
+ Thite, Anish and
67
+ Wang, Ben and
68
+ Wang, Kevin and
69
+ Zou, Andy},
70
+ title = {A framework for few-shot language model evaluation},
71
+ month = sep,
72
+ year = 2021,
73
+ publisher = {Zenodo},
74
+ version = {v0.0.1},
75
+ doi = {10.5281/zenodo.5371628},
76
+ url = {https://doi.org/10.5281/zenodo.5371628}
77
+ }
78
+ ```
79
+ For style,
80
+ ```
81
+ https://fossheim.io/writing/posts/css-text-gradient/
82
+ https://css-tricks.com/css-hover-effects-background-masks-3d/
83
+ ```
84
+
85
+
__init__.py ADDED
File without changes
app/__init__.py ADDED
File without changes
app/evaluation_scripts/__init__.py ADDED
File without changes
app/evaluation_scripts/run_eval.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from accelerate import Accelerator
3
+ from transformers import (AutoModelForCausalLM, AutoModelForSeq2SeqLM,
4
+ AutoTokenizer, set_seed)
5
+
6
+
7
+ def multi_inference_rank_eval(model_name_or_path, auto_class, ex_answer_choices, context):
8
+ accelerator = Accelerator()
9
+ set_seed(42)
10
+ model_name = model_name_or_path
11
+ if auto_class == 'Seq2SeqLM':
12
+
13
+ # e.g. 'google/t5-small-lm-adapt'
14
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
15
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
16
+ else:
17
+ # e.g. 'gpt2'
18
+ model = AutoModelForCausalLM.from_pretrained(model_name)
19
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
20
+
21
+ if tokenizer.pad_token is None:
22
+ for token in [tokenizer.eos_token, tokenizer.bos_token, tokenizer.sep_token]:
23
+ if token is not None:
24
+ tokenizer.pad_token = token
25
+ if tokenizer.pad_token is None:
26
+ raise ValueError("Please define a pad token id.")
27
+
28
+ padding = False
29
+
30
+ if auto_class == 'Seq2SeqLM':
31
+ def preprocess_function(context, ex_answer_choices):
32
+ input_texts = []
33
+ answer_choices_texts = []
34
+ input_texts.append(context)
35
+ answer_choices_texts.append(
36
+ [' ' + ans for ans in ex_answer_choices])
37
+
38
+ tokenized_inputs = tokenizer(
39
+ input_texts,
40
+ padding=padding,
41
+ max_length=1024,
42
+ truncation=True,
43
+ add_special_tokens=False,
44
+ )
45
+
46
+ tokenized_targets = [
47
+ tokenizer(
48
+ ans_choi,
49
+ padding=True,
50
+ max_length=256,
51
+ truncation=True,
52
+ )
53
+ for ans_choi in answer_choices_texts
54
+ ]
55
+
56
+ features = {
57
+ k: [
58
+ [elem for _ in range(
59
+ len(tokenized_targets[idx]["input_ids"]))]
60
+ for idx, elem in enumerate(v)
61
+ ]
62
+ for k, v in tokenized_inputs.items()
63
+ }
64
+
65
+ features["labels"] = [
66
+ tokenized_targets[0]["input_ids"]
67
+ ]
68
+
69
+ features["labels_attention_mask"] = [
70
+ tokenized_targets[0]["attention_mask"]
71
+ ]
72
+ return features
73
+ else:
74
+ def preprocess_function(context, ex_answer_choices):
75
+ input_texts = []
76
+ answer_choices_texts = []
77
+ input_texts.append(context)
78
+ answer_choices_texts.append(
79
+ [' ' + ans for ans in ex_answer_choices])
80
+
81
+ tokenized_inputs = tokenizer(
82
+ input_texts,
83
+ padding=padding,
84
+ max_length=1024,
85
+ truncation=True,
86
+ add_special_tokens=False,
87
+ )
88
+
89
+ tokenized_targets = [
90
+ tokenizer(
91
+ ans_choi,
92
+ padding=True,
93
+ max_length=256,
94
+ truncation=True,
95
+ )
96
+ for ans_choi in answer_choices_texts
97
+ ]
98
+
99
+ features = {
100
+ k: [
101
+ [elem for _ in range(
102
+ len(tokenized_targets[idx]["input_ids"]))]
103
+ for idx, elem in enumerate(v)
104
+ ]
105
+ for k, v in tokenized_inputs.items()
106
+ }
107
+
108
+ features["labels"] = [
109
+ tokenized_targets[0]["input_ids"]
110
+ ]
111
+
112
+ features["labels_attention_mask"] = [
113
+ tokenized_targets[0]["attention_mask"]
114
+ ]
115
+
116
+ features["labels"] = [
117
+ [features["input_ids"][0][i][1:] + tokenized_targets[0]["input_ids"][i]
118
+ for i in range(len(tokenized_targets[0]["input_ids"]))]
119
+ ]
120
+ features["input_ids"] = [
121
+ [features["input_ids"][0][i] + tokenized_targets[0]["input_ids"][i][:-1]
122
+ for i in range(len(tokenized_targets[0]["input_ids"]))]
123
+ ]
124
+
125
+ features["labels_attention_mask"] = [
126
+ [[0] * (len(features["attention_mask"][0][i])-1) + tokenized_targets[0]
127
+ ["attention_mask"][i] for i in range(len(tokenized_targets[0]["input_ids"]))]
128
+ ]
129
+
130
+ features["attention_mask"] = [
131
+ [features["attention_mask"][0][i] + tokenized_targets[0]["attention_mask"][i][:-1]
132
+ for i in range(len(tokenized_targets[0]["input_ids"]))]
133
+ ]
134
+
135
+ return features
136
+
137
+ device = accelerator.device
138
+ model.to(device)
139
+ batch = preprocess_function(context, ex_answer_choices)
140
+ batch = {
141
+ k: torch.tensor(batch[k][0]).to(device)
142
+ for k in batch.keys()
143
+ }
144
+
145
+ model.eval()
146
+ with torch.no_grad():
147
+ model_inputs = {
148
+ k: batch[k]
149
+ for k in (["input_ids", "attention_mask", "labels"] if auto_class == 'Seq2SeqLM' else ["input_ids", "attention_mask"])
150
+ }
151
+
152
+ logits = model(**model_inputs).logits
153
+ masked_log_probs = batch["labels_attention_mask"].unsqueeze(
154
+ -1) * torch.log_softmax(logits, dim=-1)
155
+ seq_token_log_probs = torch.gather(
156
+ masked_log_probs, -1, batch["labels"].unsqueeze(-1))
157
+ seq_log_prob = seq_token_log_probs.squeeze(dim=-1).sum(dim=-1)
158
+ seq_log_prob = seq_log_prob.view(1, -1)
159
+ predictions = seq_log_prob.argmax(dim=-1)
160
+
161
+ predictions = accelerator.gather(predictions)
162
+ return predictions.item()
163
+
164
+
165
+ if __name__ == "__main__":
166
+ multi_inference_rank_eval('google/t5-small-lm-adapt', 'Seq2SeqLM',
167
+ ['True', 'False', 'True', 'Ken'], 'I am Ken. True or False')
168
+ # multi_inference_rank_eval('gpt2', 'CausalLM', ['True', 'False', 'True', 'Ken'], 'I am Ken. True or False')
app/main_page.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import streamlit.components.v1 as stc
3
+
4
+ st.set_page_config(
5
+ page_title="Example", layout="wide"
6
+ )
7
+
8
+ #style taken from https://fossheim.io/writing/posts/css-text-gradient/
9
+ stc.html("""
10
+ <meta name="viewport" content="width=device-width, initial-scale=1">
11
+ <style>
12
+
13
+ body {
14
+ margin: 0;
15
+ font-family: Arial;
16
+ }
17
+ .gradient-text {
18
+ /* Fallback: Set a background color. */
19
+ background-color: red;
20
+
21
+ /* Create the gradient. */
22
+ background-image: linear-gradient(45deg, #f3ec78, #af4261);
23
+
24
+ /* Set the background size and repeat properties. */
25
+ background-size: 100%;
26
+ background-repeat: repeat;
27
+
28
+ /* Use the text as a mask for the background. */
29
+ /* This will show the gradient as a text color rather than element bg. */
30
+ -webkit-background-clip: text;
31
+ -webkit-text-fill-color: transparent;
32
+ -moz-background-clip: text;
33
+ -moz-text-fill-color: transparent;
34
+ }
35
+
36
+
37
+
38
+ h1 {
39
+ font-family: "Archivo Black", sans-serif;
40
+ font-weight: normal;
41
+ font-size: 8em;
42
+ text-align: center;
43
+ margin-bottom: 0;
44
+ margin-bottom: -0.25em;
45
+ }
46
+ </style>
47
+
48
+ </head>
49
+ <body>
50
+
51
+ <h1 class="gradient-text">Multiple Choice<br>QA<br></h1>
52
+
53
+
54
+
55
+ </body>
56
+ </html>
57
+
58
+ """, height=1000)
59
+
60
+ st.sidebar.markdown("# Home Page 🤗")
app/pages/02_evaluation.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import streamlit as st
3
+ import requests
4
+ from typing import Dict
5
+ import os
6
+ import sys
7
+
8
+ sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
9
+ from app.evaluation_scripts.run_eval import multi_inference_rank_eval
10
+
11
+
12
+ st.set_page_config(layout="wide")
13
+ st.markdown(f'<p style="text-align:center;background-image: linear-gradient(to right,#1aa3ff, #00ff00);color:#ffffff;font-size: 4em;;border-radius:2%;-webkit-background-clip: text;-webkit-text-fill-color: transparent;">Submit your question here</p>', unsafe_allow_html=True)
14
+
15
+
16
+ st.sidebar.markdown("# Evaluation 🤔")
17
+ st.markdown(
18
+ '<style>div[data-testid="stHorizontalBlock"] > div:first-of-type {border:10px;padding:30px;border-radius: 10px;;background-image: linear-gradient(45deg, #1aa3ff, #234599);}</style>', unsafe_allow_html=True)
19
+ st.markdown(
20
+ '<style>div[data-testid="stHorizontalBlock"] > div:nth-of-type(2) {border:10px;padding:30px;border-radius: 10px;background-image: linear-gradient(45deg, #f3ec78, #023611);}</style>', unsafe_allow_html=True)
21
+
22
+
23
+
24
+ INCLUDED_USERS = ['google', 'EleutherAI',
25
+ "bigscience", "facebook", "openai", "microsoft"]
26
+
27
+ PIPELINE_TAG_TO_TASKS = {
28
+ 'text-generation': "CausalLM", 'text2text-generation': "Seq2SeqLM"}
29
+
30
+
31
+ @st.cache
32
+ def fetch_model_info_from_huggingface_api() -> Dict[str, Dict[str, str]]:
33
+ requests.get("https://huggingface.co")
34
+ response = requests.get("https://huggingface.co/api/models")
35
+ tags = response.json()
36
+ model_to_model_id = {}
37
+ model_to_pipeline_tag = {}
38
+
39
+ for model in tags:
40
+ model_name = model['modelId']
41
+ is_community_model = "/" in model_name
42
+ if is_community_model:
43
+ user = model_name.split("/")[0]
44
+ if user not in INCLUDED_USERS:
45
+ continue
46
+ if "pipeline_tag" in model and model["pipeline_tag"] in list(PIPELINE_TAG_TO_TASKS.keys()):
47
+ model_to_model_id[model['id']] = model['modelId']
48
+ model_to_pipeline_tag[model['id']
49
+ ] = PIPELINE_TAG_TO_TASKS[model["pipeline_tag"]]
50
+ return model_to_pipeline_tag
51
+
52
+
53
+ model_to_auto_class = fetch_model_info_from_huggingface_api()
54
+
55
+ col1, col2 = st.columns([3, 2])
56
+ user_input = {}
57
+ with col1:
58
+ st.header("Question")
59
+ user_input['context'] = st.text_input(
60
+ label='Write your question. You may explicity mention the answer choices in the prompt.', value='Huggingface is awesome. True or False?')
61
+ user_input['answer_choices_texts'] = st.text_input(
62
+ label='Add answer choices in text spearated by a comma and a space.', value='True, False')
63
+ user_input['answer_choices_texts'] = user_input['answer_choices_texts'].split(
64
+ ', ')
65
+
66
+
67
+ with col2:
68
+ st.header("Model Config")
69
+ user_input['model'] = st.selectbox(
70
+ "Which model?", list(model_to_auto_class.keys()))
71
+ user_input['auto_class'] = model_to_auto_class[user_input['model']]
72
+ col4, col5 = st.columns(2)
73
+ with col5:
74
+ #style taken from https://css-tricks.com/css-hover-effects-background-masks-3d/
75
+ st.markdown("""<style>
76
+ div.stButton > button:first-child {
77
+ width: 100%;
78
+ border: 4px solid;
79
+ border-image: repeating-linear-gradient(135deg,#F8CA00 0 10px,#E97F02 0 20px,#BD1550 0 30px) 8;
80
+ -webkit-mask:
81
+ conic-gradient(from 180deg at top 8px right 8px, #0000 90deg,#000 0)
82
+ var(--_i,200%) 0 /200% var(--_i,8px) border-box no-repeat,
83
+ conic-gradient(at bottom 8px left 8px, #0000 90deg,#000 0)
84
+ 0 var(--_i,200%)/var(--_i,8px) 200% border-box no-repeat,
85
+ linear-gradient(#000 0 0) padding-box no-repeat;
86
+ transition: .3s, -webkit-mask-position .3s .3s;
87
+
88
+ }
89
+ button:hover {
90
+ --_i: 100%;
91
+ color: #CC333F;
92
+ transition: .3s, -webkit-mask-size .3s .3s;
93
+ }
94
+ </style>""", unsafe_allow_html=True)
95
+ st.header("Submit task")
96
+ submit = st.button('Submit')
97
+
98
+ with col4:
99
+ st.header("Result")
100
+ if submit:
101
+ with st.spinner('Wait for it...'):
102
+ prediction = multi_inference_rank_eval(
103
+ user_input['model'], user_input['auto_class'], user_input['answer_choices_texts'], user_input['context'])
104
+ # print(prediction)
105
+ st.markdown(f"### {user_input['answer_choices_texts'][prediction]}")
app/pages/03_reference.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ st.set_page_config(layout="wide")
4
+ st.markdown(f'<p style="text-align:center;background-image: linear-gradient(to right,#d9306e, #412f8f);color:#ffffff;font-size: 4em;;border-radius:2%;-webkit-background-clip: text;-webkit-text-fill-color: transparent;">Reference</p>', unsafe_allow_html=True)
5
+
6
+ st.markdown('### A chunk of codes used for this projects is taken and insipred from the following works and their related repository:')
7
+
8
+ st.markdown("""1. @inproceedings{sanh2022multitask,
9
+ title={Multitask Prompted Training Enables Zero-Shot Task Generalization},
10
+ author={Victor Sanh and Albert Webson and Colin Raffel and Stephen Bach and Lintang Sutawika and Zaid Alyafeai and Antoine Chaffin and Arnaud Stiegler and Arun Raja and Manan Dey and M Saiful Bari and Canwen Xu and Urmish Thakker and Shanya Sharma Sharma and Eliza Szczechla and Taewoon Kim and Gunjan Chhablani and Nihal Nayak and Debajyoti Datta and Jonathan Chang and Mike Tian-Jian Jiang and Han Wang and Matteo Manica and Sheng Shen and Zheng Xin Yong and Harshit Pandey and Rachel Bawden and Thomas Wang and Trishala Neeraj and Jos Rozen and Abheesht Sharma and Andrea Santilli and Thibault Fevry and Jason Alan Fries and Ryan Teehan and Teven Le Scao and Stella Biderman and Leo Gao and Thomas Wolf and Alexander M Rush},
11
+ booktitle={International Conference on Learning Representations},
12
+ year={2022}
13
+ url={https://openreview.net/forum?id=9Vrb9D0WI4}""")
14
+
15
+ st.markdown("""2. @software{eval-harness, author = {Gao, Leo and
16
+ Tow, Jonathan and
17
+ Biderman, Stella and
18
+ Black, Sid and
19
+ DiPofi, Anthony and
20
+ Foster, Charles and
21
+ Golding, Laurence and
22
+ Hsu, Jeffrey and
23
+ McDonell, Kyle and
24
+ Muennighoff, Niklas and
25
+ Phang, Jason and
26
+ Reynolds, Laria and
27
+ Tang, Eric and
28
+ Thite, Anish and
29
+ Wang, Ben and
30
+ Wang, Kevin and
31
+ Zou, Andy},
32
+ title = {A framework for few-shot language model evaluation},
33
+ month = sep,
34
+ year = 2021,
35
+ publisher = {Zenodo},
36
+ version = {v0.0.1},
37
+ doi = {10.5281/zenodo.5371628},
38
+ url = {https://doi.org/10.5281/zenodo.5371628}
39
+ }
40
+ }""")
41
+
42
+ st.markdown("""3. For style https://fossheim.io/writing/posts/css-text-gradient/""")
43
+ st.markdown("""4. For style https://css-tricks.com/css-hover-effects-background-masks-3d/""")
assets/demo.png ADDED

Git LFS Details

  • SHA256: f4bbf362239ecf5366ce98ac63c3851e7a8c8bdc5ee7dbf5aa2c9793a0509e06
  • Pointer size: 132 Bytes
  • Size of remote file: 1.08 MB
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit==1.10.0
2
+ torch
3
+ transformers[sentencepiece]
4
+ accelerate