├── .gitignore ├── LICENSE ├── README.md ├── demo.py ├── gliclass ├── __init__.py ├── config.py ├── data_processing.py ├── layers.py ├── loss_functions.py ├── model.py ├── pipeline.py ├── poolings.py ├── scorers.py ├── training.py └── utils.py ├── notebooks └── finetuning.ipynb ├── pyproject.toml ├── test_gliclass.py ├── train.py └── train_rl.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | #custom 10 | models/ 11 | wandb/ 12 | gradio_cached_examples/ 13 | test.ipynb 14 | demo1.py 15 | .gradio/ 16 | 17 | # Distribution / packaging 18 | .Python 19 | build/ 20 | develop-eggs/ 21 | dist/ 22 | downloads/ 23 | eggs/ 24 | .eggs/ 25 | lib/ 26 | lib64/ 27 | parts/ 28 | sdist/ 29 | var/ 30 | wheels/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .nox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *.cover 57 | *.py,cover 58 | .hypothesis/ 59 | .pytest_cache/ 60 | cover/ 61 | 62 | # Translations 63 | *.mo 64 | *.pot 65 | 66 | # Django stuff: 67 | *.log 68 | local_settings.py 69 | db.sqlite3 70 | db.sqlite3-journal 71 | 72 | # Flask stuff: 73 | instance/ 74 | .webassets-cache 75 | 76 | # Scrapy stuff: 77 | .scrapy 78 | 79 | # Sphinx documentation 80 | docs/_build/ 81 | 82 | # PyBuilder 83 | .pybuilder/ 84 | target/ 85 | 86 | # Jupyter Notebook 87 | .ipynb_checkpoints 88 | 89 | # IPython 90 | profile_default/ 91 | ipython_config.py 92 | 93 | # pyenv 94 | # For a library or package, you might want to ignore these files since the code is 95 | # intended to run in multiple environments; otherwise, check them in: 96 | # .python-version 97 | 98 | # pipenv 99 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 100 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 101 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 102 | # install all needed dependencies. 103 | #Pipfile.lock 104 | 105 | # poetry 106 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 107 | # This is especially recommended for binary packages to ensure reproducibility, and is more 108 | # commonly ignored for libraries. 109 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 110 | #poetry.lock 111 | 112 | # pdm 113 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 114 | #pdm.lock 115 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 116 | # in version control. 117 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 118 | .pdm.toml 119 | .pdm-python 120 | .pdm-build/ 121 | 122 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 123 | __pypackages__/ 124 | 125 | # Celery stuff 126 | celerybeat-schedule 127 | celerybeat.pid 128 | 129 | # SageMath parsed files 130 | *.sage.py 131 | 132 | # Environments 133 | .env 134 | .venv 135 | env/ 136 | venv/ 137 | ENV/ 138 | env.bak/ 139 | venv.bak/ 140 | 141 | # Spyder project settings 142 | .spyderproject 143 | .spyproject 144 | 145 | # Rope project settings 146 | .ropeproject 147 | 148 | # mkdocs documentation 149 | /site 150 | 151 | # mypy 152 | .mypy_cache/ 153 | .dmypy.json 154 | dmypy.json 155 | 156 | # Pyre type checker 157 | .pyre/ 158 | 159 | # pytype static type analyzer 160 | .pytype/ 161 | 162 | # Cython debug symbols 163 | cython_debug/ 164 | 165 | # PyCharm 166 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 167 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 168 | # and can be added to the global gitignore or merged into this file. For a more nuclear 169 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 170 | #.idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ⭐ GLiClass: Generalist and Lightweight Model for Sequence Classification 2 | 3 | **GLiClass** is an efficient, zero-shot sequence classification model inspired by the [GLiNER](https://github.com/urchade/GLiNER/tree/main) framework. It achieves comparable performance to traditional cross-encoder models while being significantly more computationally efficient, offering classification results approximately **10 times faster** by performing classification in a single forward pass. 4 | 5 |

6 | 📄 Blog 7 |   •   8 | 📢 Discord 9 |   •   10 | 📺 Demo 11 |   •   12 | 🤗 Available models 13 |   •   14 | 15 | 16 | 17 |

18 | 19 | ### 🚀 Quick Start 20 | 21 | Install GLiClass easily using pip: 22 | 23 | ```bash 24 | pip install gliclass 25 | ``` 26 | 27 | #### Install from Source 28 | 29 | Clone and install directly from GitHub: 30 | 31 | ```bash 32 | git clone https://github.com/Knowledgator/GLiClass 33 | cd GLiClass 34 | 35 | python -m venv venv 36 | source venv/bin/activate # Windows: venv\Scripts\activate 37 | 38 | pip install -r requirements.txt 39 | pip install . 40 | ``` 41 | 42 | Verify your installation: 43 | 44 | ```python 45 | import gliclass 46 | print(gliclass.__version__) 47 | ``` 48 | 49 | ### 🧑‍💻 Usage Example 50 | 51 | ```python 52 | from gliclass import GLiClassModel, ZeroShotClassificationPipeline 53 | from transformers import AutoTokenizer 54 | 55 | model = GLiClassModel.from_pretrained("knowledgator/gliclass-small-v1.0") 56 | tokenizer = AutoTokenizer.from_pretrained("knowledgator/gliclass-small-v1.0") 57 | 58 | pipeline = ZeroShotClassificationPipeline( 59 | model, tokenizer, classification_type='multi-label', device='cuda:0' 60 | ) 61 | 62 | text = "One day I will see the world!" 63 | labels = ["travel", "dreams", "sport", "science", "politics"] 64 | results = pipeline(text, labels, threshold=0.5)[0] 65 | 66 | for result in results: 67 | print(f"{result['label']} => {result['score']:.3f}") 68 | ``` 69 | 70 | ### 🌟 Retrieval-Augmented Classification (RAC) 71 | 72 | With new models trained with retrieval-agumented classification, such as [this model](https://huggingface.co/knowledgator/gliclass-base-v2.0-rac-init) you can specify examples to improve classification accuracy: 73 | 74 | ```python 75 | example = { 76 | "text": "A new machine learning platform automates complex data workflows but faces integration issues.", 77 | "all_labels": ["AI", "automation", "data_analysis", "usability", "integration"], 78 | "true_labels": ["AI", "integration", "automation"] 79 | } 80 | 81 | text = "The new AI-powered tool streamlines data analysis but has limited integration capabilities." 82 | labels = ["AI", "automation", "data_analysis", "usability", "integration"] 83 | 84 | results = pipeline(text, labels, threshold=0.1, rac_examples=[example])[0] 85 | 86 | for predict in results: 87 | print(f"{predict['label']} => {predict['score']:.3f}") 88 | ``` 89 | 90 | ### 🎯 Key Use Cases 91 | 92 | - **Sentiment Analysis:** Rapidly classify texts as positive, negative, or neutral. 93 | - **Document Classification:** Efficiently organize and categorize large document collections. 94 | - **Search Results Re-ranking:** Improve relevance and precision by reranking search outputs. 95 | - **News Categorization:** Automatically tag and organize news articles into predefined categories. 96 | - **Fact Checking:** Quickly validate and categorize statements based on factual accuracy. 97 | 98 | ### 🛠️ How to Train 99 | 100 | Prepare your training data as follows: 101 | 102 | ```json 103 | [ 104 | {"text": "Sample text.", "all_labels": ["sports", "science", "business"], "true_labels": ["sports"]}, 105 | ... 106 | ] 107 | ``` 108 | 109 | Optionally, specify confidence scores explicitly: 110 | 111 | ```json 112 | [ 113 | {"text": "Sample text.", "all_labels": ["sports", "science"], "true_labels": {"sports": 0.9}}, 114 | ... 115 | ] 116 | ``` 117 | 118 | Please, refer to the `train.py` script to set up your training from scratch or fine-tune existing models. 119 | -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | from typing import Dict, Union 2 | import gradio as gr 3 | import torch 4 | from transformers import AutoTokenizer 5 | 6 | from gliclass import GLiClassModel, ZeroShotClassificationPipeline 7 | 8 | device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') 9 | 10 | model_path = "models/checkpoint-1000" 11 | model = GLiClassModel.from_pretrained(model_path) 12 | tokenizer = AutoTokenizer.from_pretrained(model_path) 13 | 14 | 15 | pipeline = ZeroShotClassificationPipeline(model, tokenizer, classification_type='multi-label', device='cuda') 16 | 17 | text1 = """ 18 | "I recently purchased the Sony WH-1000XM4 Wireless Noise-Canceling Headphones from Amazon and I must say, I'm thoroughly impressed. The package arrived in New York within 2 days, thanks to Amazon Prime's expedited shipping. 19 | 20 | The headphones themselves are remarkable. The noise-canceling feature works like a charm in the bustling city environment, and the 30-hour battery life means I don't have to charge them every day. Connecting them to my Samsung Galaxy S21 was a breeze, and the sound quality is second to none. 21 | 22 | I also appreciated the customer service from Amazon when I had a question about the warranty. They responded within an hour and provided all the information I needed. 23 | 24 | However, the headphones did not come with a hard case, which was listed in the product description. I contacted Amazon, and they offered a 10% discount on my next purchase as an apology. 25 | 26 | Overall, I'd give these headphones a 4.5/5 rating and highly recommend them to anyone looking for top-notch quality in both product and service.""" 27 | 28 | text2 = """ 29 | Apple Inc. is an American multinational technology company headquartered in Cupertino, California. Apple is the world's largest technology company by revenue, with US$394.3 billion in 2022 revenue. As of March 2023, Apple is the world's biggest company by market capitalization. As of June 2022, Apple is the fourth-largest personal computer vendor by unit sales and the second-largest mobile phone manufacturer in the world. It is considered one of the Big Five American information technology companies, alongside Alphabet (parent company of Google), Amazon, Meta Platforms, and Microsoft. 30 | Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975 to develop and sell BASIC interpreters for the Altair 8800. During his career at Microsoft, Gates held the positions of chairman, chief executive officer, president and chief software architect, while also being the largest individual shareholder until May 2014. 31 | Apple was founded as Apple Computer Company on April 1, 1976, by Steve Wozniak, Steve Jobs (1955–2011) and Ronald Wayne to develop and sell Wozniak's Apple I personal computer. It was incorporated by Jobs and Wozniak as Apple Computer, Inc. in 1977. The company's second computer, the Apple II, became a best seller and one of the first mass-produced microcomputers. Apple went public in 1980 to instant financial success. The company developed computers featuring innovative graphical user interfaces, including the 1984 original Macintosh, announced that year in a critically acclaimed advertisement called "1984". By 1985, the high cost of its products, and power struggles between executives, caused problems. Wozniak stepped back from Apple and pursued other ventures, while Jobs resigned and founded NeXT, taking some Apple employees with him. 32 | """ 33 | 34 | text3 = """ 35 | Several studies have reported its pharmacological activities, including anti-inflammatory, antimicrobial, and antitumoral effects. 36 | The effect of E-anethole was studied in the osteosarcoma MG-63 cell line, and the antiproliferative activity was evaluated by an MTT assay. 37 | It showed a GI50 value of 60.25 μM with apoptosis induction through the mitochondrial-mediated pathway. Additionally, it induced cell cycle arrest at the G0/G1 phase, up-regulated the expression of p53, caspase-3, and caspase-9, and down-regulated Bcl-xL expression. 38 | Moreover, the antitumoral activity of anethole was assessed against oral tumor Ca9-22 cells, and the cytotoxic effects were evaluated by MTT and LDH assays. 39 | It demonstrated a LD50 value of 8 μM, and cellular proliferation was 42.7% and 5.2% at anethole concentrations of 3 μM and 30 μM, respectively. 40 | It was reported that it could selectively and in a dose-dependent manner decrease cell proliferation and induce apoptosis, as well as induce autophagy, decrease ROS production, and increase glutathione activity. The cytotoxic effect was mediated through NF-kB, MAP kinases, Wnt, caspase-3 and -9, and PARP1 pathways. Additionally, treatment with anethole inhibited cyclin D1 oncogene expression, increased cyclin-dependent kinase inhibitor p21WAF1, up-regulated p53 expression, and inhibited the EMT markers. 41 | """ 42 | examples = [ 43 | [ 44 | text1, 45 | "product review, sport, competition, electronics, positive feadback, negative feadback", 46 | 0.5, 47 | False 48 | ], 49 | [ 50 | text2, 51 | "business, computers, sport, politics, science", 52 | 0.5, 53 | False 54 | ], 55 | [ 56 | text3, 57 | "business, biology, science, politics, positive review", 58 | 0.5, 59 | False 60 | ], 61 | ] 62 | 63 | def classification( 64 | text, labels: str, threshold: float, multi_label: bool = False 65 | ) -> str: 66 | labels = labels.split(",") 67 | if multi_label: 68 | pipeline.pipe.classification_type = 'multi-label' 69 | else: 70 | pipeline.pipe.classification_type = 'single-label' 71 | 72 | results = pipeline(text, labels, threshold=threshold)[0] #because we have one text 73 | 74 | predicts = {result['label']:float(result['score']) for result in results} 75 | # predicts = '\n'.join([f"{result['label']} => {result['score']}" for result in results]) 76 | return predicts 77 | 78 | 79 | with gr.Blocks(title="GLiClass-small-v1.0") as demo: 80 | with gr.Accordion("How to run this model locally", open=False): 81 | gr.Markdown( 82 | """ 83 | ## Installation 84 | To use this model, you must install the GLiClass Python library: 85 | ``` 86 | !pip install gliclass 87 | ``` 88 | 89 | ## Usage 90 | Once you've downloaded the GLiClass library, you can import the GLiClassModel and ZeroShotClassificationPipeline classes. 91 | """ 92 | ) 93 | gr.Code( 94 | ''' 95 | from gliclass import GLiClassModel, ZeroShotClassificationPipeline 96 | from transformers import AutoTokenizer 97 | 98 | model = GLiClassModel.from_pretrained("knowledgator/gliclass-small-v1") 99 | tokenizer = AutoTokenizer.from_pretrained("knowledgator/gliclass-small-v1") 100 | 101 | pipeline = ZeroShotClassificationPipeline(model, tokenizer, classification_type='multi-label', device='cuda:0') 102 | 103 | text = "One day I will see the world!" 104 | labels = ["travel", "dreams", "sport", "science", "politics"] 105 | results = pipeline(text, labels, threshold=0.5)[0] #because we have one text 106 | 107 | for result in results: 108 | print(result["label"], "=>", result["score"]) 109 | ''', 110 | language="python", 111 | ) 112 | 113 | input_text = gr.Textbox( 114 | value=examples[0][0], label="Text input", placeholder="Enter your text here" 115 | ) 116 | with gr.Row() as row: 117 | labels = gr.Textbox( 118 | value=examples[0][1], 119 | label="Labels", 120 | placeholder="Enter your labels here (comma separated)", 121 | scale=2, 122 | ) 123 | threshold = gr.Slider( 124 | 0, 125 | 1, 126 | value=0.3, 127 | step=0.01, 128 | label="Threshold", 129 | info="Lower the threshold to increase how many entities get predicted.", 130 | scale=1, 131 | ) 132 | multi_label = gr.Checkbox( 133 | value=examples[0][2], 134 | label="Multi-label classification", 135 | info="Allow for multi-label classification?", 136 | scale=0, 137 | ) 138 | output = gr.Label(label="Output", color="#4b5563") 139 | submit_btn = gr.Button("Submit") 140 | examples = gr.Examples( 141 | examples, 142 | fn=classification, 143 | inputs=[input_text, labels, threshold, multi_label], 144 | outputs=output, 145 | cache_examples=True, 146 | ) 147 | 148 | # Submitting 149 | input_text.submit( 150 | fn=classification, inputs=[input_text, labels, threshold, multi_label], outputs=output 151 | ) 152 | labels.submit( 153 | fn=classification, inputs=[input_text, labels, threshold, multi_label], outputs=output 154 | ) 155 | threshold.release( 156 | fn=classification, inputs=[input_text, labels, threshold, multi_label], outputs=output 157 | ) 158 | submit_btn.click( 159 | fn=classification, inputs=[input_text, labels, threshold, multi_label], outputs=output 160 | ) 161 | multi_label.change( 162 | fn=classification, inputs=[input_text, labels, threshold, multi_label], outputs=output 163 | ) 164 | 165 | demo.queue() 166 | demo.launch(debug=True, share=True) -------------------------------------------------------------------------------- /gliclass/__init__.py: -------------------------------------------------------------------------------- 1 | from .model import GLiClassModel, GLiClassBiEncoder, GLiClassUniEncoder 2 | from .config import GLiClassModelConfig 3 | from .pipeline import ZeroShotClassificationPipeline, BiEncoderZeroShotClassificationPipeline, ZeroShotClassificationWithLabelsChunkingPipeline -------------------------------------------------------------------------------- /gliclass/config.py: -------------------------------------------------------------------------------- 1 | from transformers import AutoConfig 2 | from transformers.configuration_utils import PretrainedConfig 3 | from transformers.utils import logging 4 | from transformers.models.auto import CONFIG_MAPPING 5 | logger = logging.get_logger(__name__) 6 | 7 | 8 | class GLiClassModelConfig(PretrainedConfig): 9 | model_type = "GLiClass" 10 | is_composition = True 11 | 12 | def __init__( 13 | self, 14 | encoder_config = None, 15 | encoder_model=None, 16 | label_model_config=None, 17 | label_model_name=None, 18 | class_token_index = -1, 19 | text_token_index = -1, 20 | ignore_index=-100, 21 | hidden_size=None, 22 | projector_hidden_act="gelu", 23 | vocab_size=None, 24 | problem_type='single_label_classification', 25 | max_num_classes=25, 26 | use_lstm=False, 27 | initializer_range=0.03, 28 | scorer_type='simple', 29 | pooling_strategy='first', 30 | focal_loss_alpha=0.5, 31 | focal_loss_gamma=2, 32 | logit_scale_init_value=2.6592, 33 | normalize_features=False, 34 | extract_text_features=False, 35 | contrastive_loss_coef=0, 36 | architecture_type = 'uni-encoder', 37 | prompt_first = False, 38 | squeeze_layers = False, 39 | embed_class_token = True, 40 | **kwargs, 41 | ): 42 | if isinstance(encoder_config, dict): 43 | encoder_config["model_type"] = (encoder_config["model_type"] 44 | if "model_type" in encoder_config 45 | else "deberta-v2") 46 | encoder_config = CONFIG_MAPPING[encoder_config["model_type"]](**encoder_config) 47 | elif encoder_config is None: 48 | encoder_config = CONFIG_MAPPING["deberta-v2"]() 49 | 50 | self.encoder_config = encoder_config 51 | self.encoder_model_name = encoder_model 52 | 53 | if label_model_name is not None: 54 | if isinstance(label_model_config, dict): 55 | label_model_config["model_type"] = (label_model_config["model_type"] 56 | if "model_type" in label_model_config 57 | else "deberta-v2") 58 | label_model_config = CONFIG_MAPPING[label_model_config["model_type"]](**label_model_config) 59 | elif label_model_config is None: 60 | label_model_config = CONFIG_MAPPING["deberta-v2"]() 61 | 62 | self.label_model_config = label_model_config 63 | else: 64 | self.label_model_config = None 65 | self.label_model_name = label_model_name 66 | 67 | if hidden_size is None: 68 | self.hidden_size = self.encoder_config.hidden_size 69 | else: 70 | self.hidden_size = hidden_size 71 | 72 | if vocab_size is None: 73 | self.vocab_size = self.encoder_config.vocab_size 74 | else: 75 | self.vocab_size = vocab_size 76 | 77 | if class_token_index == -1: 78 | self.class_token_index = self.vocab_size 79 | else: 80 | self.class_token_index = class_token_index 81 | 82 | if text_token_index == -1: 83 | self.text_token_index = self.vocab_size+1 84 | else: 85 | self.text_token_index = text_token_index 86 | 87 | self.ignore_index = ignore_index 88 | self.projector_hidden_act = projector_hidden_act 89 | self.problem_type = problem_type 90 | self.max_num_classes = max_num_classes 91 | self.initializer_range=initializer_range 92 | self.scorer_type = scorer_type 93 | self.pooling_strategy=pooling_strategy 94 | self.use_lstm = use_lstm 95 | self.focal_loss_alpha=focal_loss_alpha 96 | self.focal_loss_gamma=focal_loss_gamma 97 | self.contrastive_loss_coef=contrastive_loss_coef 98 | self.logit_scale_init_value = logit_scale_init_value 99 | self.normalize_features=normalize_features 100 | self.extract_text_features = extract_text_features 101 | self.architecture_type = architecture_type 102 | self.prompt_first = prompt_first 103 | self.squeeze_layers = squeeze_layers 104 | self.embed_class_token = embed_class_token 105 | super().__init__(**kwargs) 106 | 107 | -------------------------------------------------------------------------------- /gliclass/data_processing.py: -------------------------------------------------------------------------------- 1 | import random 2 | import torch 3 | from torch.nn.utils.rnn import pad_sequence 4 | from torch.utils.data import Dataset 5 | 6 | 7 | class GLiClassDataset(Dataset): 8 | def __init__(self, examples, tokenizer, max_length=512, 9 | problem_type='multi_label_classification', 10 | architecture_type = 'uni-encoder', 11 | prompt_first=False, 12 | get_negatives = False, 13 | max_labels = 50, 14 | labels_tokenizer=None, 15 | shuffle_labels = True): 16 | self.tokenizer = tokenizer 17 | self.labels_tokenizer = labels_tokenizer 18 | self.max_length = max_length 19 | self._data = examples 20 | self.problem_type = problem_type 21 | self.architecture_type = architecture_type 22 | self.prompt_first = prompt_first 23 | self.dataset_labels = self.collect_dataset_labels() 24 | self.get_negatives = get_negatives 25 | self.max_labels = max_labels 26 | self.shuffle_labels = shuffle_labels 27 | print('Total labels: ', len(self.dataset_labels)) 28 | 29 | def collect_dataset_labels(self): 30 | dataset_labels = set() 31 | for example in self._data: 32 | dataset_labels.update(set(example['all_labels'])) 33 | return dataset_labels 34 | 35 | def prepare_labels(self, example, label2idx, problem_type): 36 | if problem_type == 'single_label_classification': 37 | labels = label2idx[example['true_labels'][0]] 38 | elif problem_type == 'multi_label_classification': 39 | if isinstance(example['true_labels'], dict): 40 | labels = [example['true_labels'][label] if label in example['true_labels'] else 0. for label in example['all_labels']] 41 | else: 42 | labels = [1. if label in example['true_labels'] else 0. for label in example['all_labels']] 43 | else: 44 | raise NotImplementedError(f"{problem_type} is not implemented.") 45 | return torch.tensor(labels) 46 | 47 | def prepare_prompt(self, example): 48 | prompt_texts = [] 49 | for label in example['all_labels']: 50 | label_tag = f"<