diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml new file mode 100644 index 00000000..4304b7c2 --- /dev/null +++ b/.github/workflows/workflow.yml @@ -0,0 +1,36 @@ +name: Publish Python 🐍 distributions 📦 to PyPI + +on: + push: + tags: + - '*' + +jobs: + build-n-publish: + name: Build and publish Python 🐍 distributions 📦 to PyPI + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.10' + - name: Install pypa/build + run: >- + python -m + pip install + build + --user + - name: Build a binary wheel and a source tarball + run: >- + python -m + build + --sdist + --wheel + --outdir dist/ + - name: Publish distribution 📦 to PyPI + if: startsWith(github.ref, 'refs/tags') + uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.pypi_password }} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f49a4e16 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 4282c46a..fdcd8166 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,6 @@ [![open issues](https://img.shields.io/github/issues-raw/open-sciencelab/GraphGen)](https://github.com/open-sciencelab/GraphGen/issues) [![issue resolution](https://img.shields.io/github/issues-closed-raw/open-sciencelab/GraphGen)](https://github.com/open-sciencelab/GraphGen/issues) - -

- English | 简体中文 -

- GraphGen: Enhancing Supervised Fine-Tuning for LLMs with Knowledge-Driven Synthetic Data Generation
@@ -93,11 +88,6 @@ Furthermore, GraphGen incorporates multi-hop neighborhood sampling to capture co ls cache/data/graphgen ``` - -## 📌 Latest Updates - -## 🌟 Key Features - ## 🏗️ System Architecture ### Directory Structure @@ -119,12 +109,5 @@ Furthermore, GraphGen incorporates multi-hop neighborhood sampling to capture co └── README.md ``` - ### Workflow ![workflow](resources/images/flow.png) - -## ⚙️ Configurations - -## 📅 Roadmap - -## 💰 Cost Analysis diff --git a/README_zh.md b/README_zh.md deleted file mode 100644 index a3140beb..00000000 --- a/README_zh.md +++ /dev/null @@ -1,35 +0,0 @@ -# GraphGen: Enhancing Supervised Fine-Tuning for LLMs with Knowledge-Driven Synthetic Data Generation - -[English](README.md) | [简体中文](README_zh.md) - -

- -

- -```text -├── baselines/ # baseline methods -├── cache/ # cache files -│ ├── data/ # generated data -│ ├── logs/ # log files -├── configs/ # configuration files -├── graphgen/ # GraphGen implementation -│ ├── operators/ # operators -│ ├── graphgen.py # main file -├── models/ # base classes -├── resources/ # static files and examples -├── scripts/ # scripts for running experiments -├── templates/ # prompt templates -├── utils/ # utility functions -├── webui/ # web interface -└── README.md -``` - -## Introduction - -GraphGen is a framework for synthetic data generation guided by knowledge graphs. - -### Workflow -![workflow](resources/images/flow.png) - -### User Interface -![ui](resources/images/interface.jpg) diff --git a/evaluate.py b/evaluate.py index 6ccdfd8f..6afb8565 100644 --- a/evaluate.py +++ b/evaluate.py @@ -5,8 +5,6 @@ import argparse import pandas as pd from dotenv import load_dotenv -import torch -import torch.multiprocessing as mp from models import LengthEvaluator, MTLDEvaluator, RewardEvaluator, TextPair, UniEvaluator from utils import logger, set_logger @@ -71,11 +69,13 @@ def evaluate_uni(corpus, uni_model_name): def clean_gpu_cache(): + import torch if torch.cuda.is_available(): torch.cuda.empty_cache() if __name__ == '__main__': + import torch.multiprocessing as mp parser = argparse.ArgumentParser() parser.add_argument('--folder', type=str, default='cache/data', help='folder to load data') diff --git a/graphgen/version.py b/graphgen/version.py new file mode 100644 index 00000000..4496c034 --- /dev/null +++ b/graphgen/version.py @@ -0,0 +1,28 @@ + +from typing import Tuple + +__version__ = '20250416' +short_version = __version__ + + +def parse_version_info(version_str: str) -> Tuple: + """Parse version from a string. + + Args: + version_str (str): A string represents a version info. + + Returns: + tuple: A sequence of integer and string represents version. + """ + _version_info = [] + for x in version_str.split('.'): + if x.isdigit(): + _version_info.append(int(x)) + elif x.find('rc') != -1: + patch_version = x.split('rc') + _version_info.append(int(patch_version[0])) + _version_info.append(f'rc{patch_version[1]}') + return tuple(_version_info) + + +version_info = parse_version_info(__version__) \ No newline at end of file diff --git a/models/evaluate/reward_evaluator.py b/models/evaluate/reward_evaluator.py index 71bd245c..a48fc7c3 100644 --- a/models/evaluate/reward_evaluator.py +++ b/models/evaluate/reward_evaluator.py @@ -1,9 +1,5 @@ from dataclasses import dataclass from tqdm import tqdm -from transformers import AutoModelForSequenceClassification, AutoTokenizer -import torch -import torch.multiprocessing as mp - from models.text.text_pair import TextPair @@ -22,6 +18,8 @@ def __post_init__(self): @staticmethod def process_chunk(rank, pairs, reward_name, max_length, return_dict): + import torch + from transformers import AutoModelForSequenceClassification, AutoTokenizer device = f'cuda:{rank}' torch.cuda.set_device(rank) @@ -47,6 +45,7 @@ def process_chunk(rank, pairs, reward_name, max_length, return_dict): return_dict[rank] = results def evaluate(self, pairs: list[TextPair]) -> list[float]: + import torch.multiprocessing as mp chunk_size = len(pairs) // self.num_gpus chunks = [] for i in range(self.num_gpus): diff --git a/models/evaluate/uni_evaluator.py b/models/evaluate/uni_evaluator.py index 9add9e59..57e73227 100644 --- a/models/evaluate/uni_evaluator.py +++ b/models/evaluate/uni_evaluator.py @@ -2,11 +2,6 @@ from dataclasses import dataclass, field from tqdm import tqdm -import torch -from torch import nn -import torch.multiprocessing as mp - -from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from models.text.text_pair import TextPair @@ -31,11 +26,14 @@ class UniEvaluator: results: dict = None def __post_init__(self): + import torch self.num_gpus = torch.cuda.device_count() self.results = {} @staticmethod def process_chunk(rank, pairs, model_name, max_length, dimension, return_dict): + import torch + from transformers import AutoTokenizer, AutoModelForSeq2SeqLM device = f'cuda:{rank}' torch.cuda.set_device(rank) @@ -44,7 +42,7 @@ def process_chunk(rank, pairs, model_name, max_length, dimension, return_dict): rank_model.to(device) rank_model.eval() - softmax = nn.Softmax(dim=1) + softmax = torch.nn.Softmax(dim=1) pos_id = tokenizer("Yes")["input_ids"][0] neg_id = tokenizer("No")["input_ids"][0] @@ -94,6 +92,7 @@ def process_chunk(rank, pairs, model_name, max_length, dimension, return_dict): return_dict[rank] = results def evaluate(self, pairs: list[TextPair]) -> list[dict]: + import torch.multiprocessing as mp final_results = [] for dimension in self.dimensions: chunk_size = len(pairs) // self.num_gpus diff --git a/requirements.txt b/requirements.txt index df071b49..190e7966 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,15 +5,14 @@ numpy networkx graspologic tiktoken -transformers pyecharts wikipedia tenacity nltk jieba -torch plotly pandas gradio kaleido pyyaml +langcodes diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..5571d7d4 --- /dev/null +++ b/setup.py @@ -0,0 +1,64 @@ +import os + +from setuptools import find_packages, setup + +pwd = os.path.dirname(__file__) +version_file = 'graphgen/version.py' + + +def readme(): + with open(os.path.join(pwd, 'README.md'), encoding='utf-8') as f: + content = f.read() + return content + + +def get_version(): + with open(os.path.join(pwd, version_file), 'r') as f: + exec(compile(f.read(), version_file, 'exec')) + return locals()['__version__'] + + +def read_requirements(): + lines = [] + with open('requirements.txt', 'r') as f: + for line in f.readlines(): + if line.startswith('#'): + continue + if 'textract' in line: + continue + if len(line) > 0: + lines.append(line) + return lines + + +install_packages = read_requirements() + +if __name__ == '__main__': + setup( + name='graphgen', + version=get_version(), + url='https://github.com/open-sciencelab/GraphGen', + description= # noqa E251 + 'GraphGen: Enhancing Supervised Fine-Tuning for LLMs with Knowledge-Driven Synthetic Data Generation', # noqa E501 + long_description=readme(), + long_description_content_type='text/markdown', + author='open-sciencelab', + author_email='open-sciencelab@pjlab.org.cn', + packages=find_packages(exclude=["models"]), + package_data={ + 'GraphGen': ['configs/*'] + }, + include_package_data=True, + install_requires=install_packages, + classifiers=[ + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', + 'Intended Audience :: Developers', + 'Intended Audience :: Education', + 'Intended Audience :: Science/Research', + ], + entry_points={'console_scripts': ['graphgen=generate:__main__']}, + ) diff --git a/webui/app.py b/webui/app.py index 93050283..edc2d945 100644 --- a/webui/app.py +++ b/webui/app.py @@ -24,6 +24,7 @@ } """ + def init_graph_gen(config: dict, env: dict) -> GraphGen: graph_gen = GraphGen() @@ -31,16 +32,15 @@ def init_graph_gen(config: dict, env: dict) -> GraphGen: graph_gen.synthesizer_llm_client = OpenAIModel( model_name=env.get("SYNTHESIZER_MODEL", ""), base_url=env.get("SYNTHESIZER_BASE_URL", ""), - api_key=env.get("SYNTHESIZER_API_KEY", "") - ) + api_key=env.get("SYNTHESIZER_API_KEY", "")) graph_gen.trainee_llm_client = OpenAIModel( model_name=env.get("TRAINEE_MODEL", ""), base_url=env.get("TRAINEE_BASE_URL", ""), - api_key=env.get("TRAINEE_API_KEY", "") - ) + api_key=env.get("TRAINEE_API_KEY", "")) - graph_gen.tokenizer_instance = Tokenizer(config.get("tokenizer", "cl100k_base")) + graph_gen.tokenizer_instance = Tokenizer( + config.get("tokenizer", "cl100k_base")) strategy_config = config.get("traverse_strategy", {}) graph_gen.traverse_strategy = TraverseStrategy( @@ -58,10 +58,8 @@ def init_graph_gen(config: dict, env: dict) -> GraphGen: return graph_gen -def run_graphgen( - *arguments: list, - progress=gr.Progress() -): + +def run_graphgen(*arguments: list, progress=gr.Progress()): # Unpack arguments config = { "if_trainee_model": arguments[0], @@ -94,7 +92,8 @@ def run_graphgen( } # Test API connection - test_api_connection(env["SYNTHESIZER_BASE_URL"], env["SYNTHESIZER_API_KEY"], env["SYNTHESIZER_MODEL"]) + test_api_connection(env["SYNTHESIZER_BASE_URL"], + env["SYNTHESIZER_API_KEY"], env["SYNTHESIZER_MODEL"]) progress(0.1, "API Connection Successful") # Initialize GraphGen @@ -127,7 +126,9 @@ def run_graphgen( for line in lines: content += line.strip() + " " size = int(config.get("chunk_size", 512)) - chunks = [content[i:i + size] for i in range(0, len(content), size)] + chunks = [ + content[i:i + size] for i in range(0, len(content), size) + ] data.extend([{"content": chunk} for chunk in chunks]) else: raise ValueError(f"Unsupported file type: {file}") @@ -159,8 +160,7 @@ def run_graphgen( mode="w", suffix=".jsonl", delete=False, # 防止自动删除 - encoding="utf-8" - ) as tmpfile: + encoding="utf-8") as tmpfile: # 假设qa_storage有导出数据的方法 json.dump(output_data, tmpfile, ensure_ascii=False) output_file = tmpfile.name @@ -168,21 +168,20 @@ def run_graphgen( progress(1.0, "Graph traversed") return output_file - except Exception as e: # pylint: disable=broad-except + except Exception as e: # pylint: disable=broad-except raise gr.Error(f"Error occurred: {str(e)}") -with gr.Blocks(title="GraphGen Demo", theme=gr.themes.Base(), css=css) as demo: +with gr.Blocks(title="GraphGen Demo", theme=gr.themes.Glass(), + css=css) as demo: # Header - gr.Image( - value=f"{root_dir}/resources/images/logo.png", - label="GraphGen Banner", - elem_id="banner", - interactive=False, - container=False, - show_download_button=False, - show_fullscreen_button=False - ) + gr.Image(value=f"{root_dir}/resources/images/logo.png", + label="GraphGen Banner", + elem_id="banner", + interactive=False, + container=False, + show_download_button=False, + show_fullscreen_button=False) lang_btn = gr.Radio( choices=[ ("English", "en"), @@ -212,10 +211,11 @@ def run_graphgen( """) with Translate( - "translation.json", - lang_btn, - placeholder_langs=["en", "zh"], - persistant=False, # True to save the language setting in the browser. Requires gradio >= 5.6.0 + "translation.json", + lang_btn, + placeholder_langs=["en", "zh"], + persistant= + False, # True to save the language setting in the browser. Requires gradio >= 5.6.0 ): lang_btn.render() @@ -224,54 +224,99 @@ def run_graphgen( "### [GraphGen](https://github.com/open-sciencelab/GraphGen) " + _("Intro") ) - if_trainee_model = gr.Checkbox( - label=_("Use Trainee Model"), - value=False, - interactive=True - ) + if_trainee_model = gr.Checkbox(label=_("Use Trainee Model"), + value=False, + interactive=True) with gr.Accordion(label=_("Model Config"), open=False): - base_url = gr.Textbox(label="Base URL", value="https://api.siliconflow.cn/v1", - info=_("Base URL Info"), interactive=True) - synthesizer_model = gr.Textbox(label="Synthesizer Model", value="Qwen/Qwen2.5-7B-Instruct", - info=_("Synthesizer Model Info"), interactive=True) - trainee_model = gr.Textbox(label="Trainee Model", value="Qwen/Qwen2.5-7B-Instruct", - info=_("Trainee Model Info"), interactive=True, - visible=(if_trainee_model.value == True)) + base_url = gr.Textbox(label="Base URL", + value="https://api.siliconflow.cn/v1", + info=_("Base URL Info"), + interactive=True) + synthesizer_model = gr.Textbox(label="Synthesizer Model", + value="Qwen/Qwen2.5-7B-Instruct", + info=_("Synthesizer Model Info"), + interactive=True) + trainee_model = gr.Textbox( + label="Trainee Model", + value="Qwen/Qwen2.5-7B-Instruct", + info=_("Trainee Model Info"), + interactive=True, + visible=(if_trainee_model.value == True)) with gr.Accordion(label=_("Generation Config"), open=False): - chunk_size = gr.Slider(label="Chunk Size", minimum=256, maximum=4096, value=512, step=256, interactive=True) - tokenizer = gr.Textbox(label="Tokenizer", value="cl100k_base", interactive=True) - qa_form = gr.Radio(choices=["atomic", "multi_hop", "open"], label="QA Form", - value="open", interactive=True) - quiz_samples = gr.Number(label="Quiz Samples", value=2, minimum=1, interactive=True, + chunk_size = gr.Slider(label="Chunk Size", + minimum=256, + maximum=4096, + value=512, + step=256, + interactive=True) + tokenizer = gr.Textbox(label="Tokenizer", + value="cl100k_base", + interactive=True) + qa_form = gr.Radio(choices=["atomic", "multi_hop", "open"], + label="QA Form", + value="open", + interactive=True) + quiz_samples = gr.Number(label="Quiz Samples", + value=2, + minimum=1, + interactive=True, visible=(if_trainee_model.value == True)) - bidirectional = gr.Checkbox(label="Bidirectional", value=True, interactive=True) - - expand_method = gr.Radio(choices=["max_width", "max_tokens"], label="Expand Method", - value="max_tokens", interactive=True) + bidirectional = gr.Checkbox(label="Bidirectional", + value=True, + interactive=True) + + expand_method = gr.Radio(choices=["max_width", "max_tokens"], + label="Expand Method", + value="max_tokens", + interactive=True) max_extra_edges = gr.Slider( - minimum=1, maximum=10, value=5, label="Max Extra Edges", - step=1, interactive=True, visible=(expand_method.value == "max_width") - ) - max_tokens = gr.Slider( - minimum=64, maximum=1024, value=256, label="Max Tokens", - step=64, interactive=True, visible=(expand_method.value != "max_width") - ) - - max_depth = gr.Slider(minimum=1, maximum=5, value=2, label="Max Depth", step=1, interactive=True) - edge_sampling = gr.Radio(choices=["max_loss", "min_loss", "random"], label="Edge Sampling", - value="max_loss", interactive=True, - visible=(if_trainee_model.value == True)) - isolated_node_strategy = gr.Radio(choices=["add", "ignore"], label="Isolated Node Strategy", - value="ignore", interactive=True) - loss_strategy = gr.Radio(choices=["only_edge", "both"], label="Loss Strategy", - value="only_edge", interactive=True) + minimum=1, + maximum=10, + value=5, + label="Max Extra Edges", + step=1, + interactive=True, + visible=(expand_method.value == "max_width")) + max_tokens = gr.Slider(minimum=64, + maximum=1024, + value=256, + label="Max Tokens", + step=64, + interactive=True, + visible=(expand_method.value + != "max_width")) + + max_depth = gr.Slider(minimum=1, + maximum=5, + value=2, + label="Max Depth", + step=1, + interactive=True) + edge_sampling = gr.Radio( + choices=["max_loss", "min_loss", "random"], + label="Edge Sampling", + value="max_loss", + interactive=True, + visible=(if_trainee_model.value == True)) + isolated_node_strategy = gr.Radio(choices=["add", "ignore"], + label="Isolated Node Strategy", + value="ignore", + interactive=True) + loss_strategy = gr.Radio(choices=["only_edge", "both"], + label="Loss Strategy", + value="only_edge", + interactive=True) # difficulty_level = gr.Radio(choices=["easy", "medium", "hard"], label="Difficulty Level", value="medium") with gr.Row(equal_height=True): with gr.Column(scale=3): - api_key = gr.Textbox(label="SiliconFlow API Key", type="password", value="") + api_key = gr.Textbox( + label="SiliconCloud Token", + type="password", + value="", + info="https://cloud.siliconflow.cn/account/ak") with gr.Column(scale=1): test_connection_btn = gr.Button("Test Connection") @@ -284,16 +329,14 @@ def run_graphgen( file_types=[".txt", ".json", ".jsonl"], interactive=True, ) - gr.Examples( - examples=[ - [f"{root_dir}/webui/examples/txt_demo.txt"], - [f"{root_dir}/webui/examples/raw_demo.jsonl"], - [f"{root_dir}/webui/examples/chunked_demo.json"], - ], - inputs=upload_file, - label="Example Files", - examples_per_page=3 - ) + gr.Examples(examples=[ + [f"{root_dir}/webui/examples/txt_demo.txt"], + [f"{root_dir}/webui/examples/raw_demo.jsonl"], + [f"{root_dir}/webui/examples/chunked_demo.json"], + ], + inputs=upload_file, + label="Example Files", + examples_per_page=3) with gr.Column(scale=1): output = gr.File( label="Output", @@ -307,43 +350,36 @@ def run_graphgen( test_connection_btn.click( test_api_connection, inputs=[base_url, api_key, synthesizer_model], - outputs=[] - ) - test_connection_btn.click( - test_api_connection, - inputs=[base_url, api_key, trainee_model], - outputs=[] - ) + outputs=[]) + test_connection_btn.click(test_api_connection, + inputs=[base_url, api_key, trainee_model], + outputs=[]) - expand_method.change( - lambda method: ( - gr.update(visible=(method == "max_width")), - gr.update(visible=(method != "max_width")) - ), - inputs=expand_method, - outputs=[max_extra_edges, max_tokens] - ) + expand_method.change(lambda method: + (gr.update(visible=(method == "max_width")), + gr.update(visible=(method != "max_width"))), + inputs=expand_method, + outputs=[max_extra_edges, max_tokens]) if_trainee_model.change( - lambda use_trainee: ( - gr.update(visible=(use_trainee == True)), - gr.update(visible=(use_trainee == True)), - gr.update(visible=(use_trainee == True)) - ), + lambda use_trainee: (gr.update(visible=(use_trainee == True)), + gr.update(visible=(use_trainee == True)), + gr.update(visible=(use_trainee == True))), inputs=if_trainee_model, - outputs=[trainee_model, quiz_samples, edge_sampling] - ) + outputs=[trainee_model, quiz_samples, edge_sampling]) # run GraphGen submit_btn.click( run_graphgen, inputs=[ - if_trainee_model, upload_file, tokenizer, qa_form, bidirectional, expand_method, max_extra_edges, - max_tokens, max_depth, edge_sampling, isolated_node_strategy, loss_strategy, - base_url, synthesizer_model, trainee_model, api_key, chunk_size + if_trainee_model, upload_file, tokenizer, qa_form, + bidirectional, expand_method, max_extra_edges, max_tokens, + max_depth, edge_sampling, isolated_node_strategy, + loss_strategy, base_url, synthesizer_model, trainee_model, + api_key, chunk_size ], outputs=[output], ) if __name__ == "__main__": - demo.launch() + demo.launch(server_name='0.0.0.0') diff --git a/webui/translation.json b/webui/translation.json index f6c8c9b0..c9a9a340 100644 --- a/webui/translation.json +++ b/webui/translation.json @@ -1,8 +1,8 @@ { "en": { "Title": "✨Easy-to-use LLM Training Data Generation Framework✨", - "Intro": "is a framework for synthetic data generation guided by knowledge graphs, designed to tackle challenges for knowledge-intensive QA generation.", - "Use Trainee Model": "Use Trainee Model to identify knowledge blind spots", + "Intro": "is a framework for synthetic data generation guided by knowledge graphs, designed to tackle challenges for knowledge-intensive QA generation. \n\nBy uploading your text chunks (such as knowledge in agriculture, healthcare, or marine science) and filling in the LLM API key, you can generate the training data required by **LLaMA-Factory** and **xtuner** online. We will automatically delete user information after completion.", + "Use Trainee Model": "Use Trainee Model to identify knowledge blind spots, disable by default", "Base URL Info": "Base URL for the API, use SiliconFlow as default", "Synthesizer Model Info": "Model for constructing KGs and generating QAs", "Trainee Model Info": "Model for training", @@ -11,8 +11,8 @@ }, "zh": { "Title": "✨开箱即用的LLM训练数据生成框架✨", - "Intro": "是一个基于知识图谱的合成数据生成框架,旨在解决知识密集型问答生成的挑战。", - "Use Trainee Model": "使用Trainee Model来识别知识盲区", + "Intro": "是一个基于知识图谱的合成数据生成框架,旨在解决知识密集型问答生成的挑战。\n\n 上传你的文本块(如农业、医疗、海洋知识),填写 LLM api key,即可在线生成 **LLaMA-Factory**、**xtuner** 所需训练数据。结束后我们将自动删除用户信息。", + "Use Trainee Model": "使用Trainee Model来识别知识盲区,默认禁用", "Base URL Info": "调用模型API的URL,默认使用硅基流动", "Synthesizer Model Info": "用于构建知识图谱和生成问答的模型", "Trainee Model Info": "用于训练的模型",