Andrewstivan commited on
Commit
119fd47
ยท
verified ยท
1 Parent(s): 0d122d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -232
app.py CHANGED
@@ -1,212 +1,13 @@
1
  import os
2
- import pathlib
3
- import random
4
- import string
5
  import tempfile
6
- import time
7
- import threading
8
- from concurrent.futures import ThreadPoolExecutor
9
- from typing import Iterable, List
10
 
11
- import gradio as gr
12
- import huggingface_hub
13
- import torch
14
- import yaml
15
- from gradio_logsview.logsview import Log, LogsView, LogsViewRunner
16
- from mergekit.config import MergeConfiguration
17
 
18
- from clean_community_org import garbage_collect_empty_models
19
-
20
- has_gpu = torch.cuda.is_available()
21
-
22
- # Running directly from Python doesn't work well with Gradio+run_process because of:
23
- # Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method
24
- # Let's use the CLI instead.
25
- #
26
- #import mergekit.merge
27
- #from mergekit.common import parse_kmb
28
- #from mergekit.options import MergeOptions
29
- #print(dir(MergeOptions))
30
- # merge_options = (
31
- # MergeOptions(
32
- # copy_tokenizer=True,
33
- # cuda=True,
34
- # low_cpu_memory=True,
35
- # write_model_card=True,
36
- # )
37
- # if has_gpu
38
- # else MergeOptions(
39
- # allow_crimes=True,
40
- # out_shard_size=parse_kmb("1B"),
41
- # lazy_unpickle=True,
42
- # write_model_card=True,
43
- # )
44
- # )
45
-
46
- cli = "mergekit-yaml config.yaml merge --copy-tokenizer" + (
47
- " --cuda --low-cpu-memory" if has_gpu else " --allow-crimes --out-shard-size 1B --lazy-unpickle"
48
- )
49
-
50
- MARKDOWN_DESCRIPTION = """
51
- # mergekit-gui
52
-
53
- The fastest way to perform a model merge ๐Ÿ”ฅ
54
-
55
- Specify a YAML configuration file (see examples below) and a HF token and this app will perform the merge and upload the merged model to your user profile.
56
- """
57
-
58
- MARKDOWN_ARTICLE = """
59
- ___
60
-
61
- ## Merge Configuration
62
-
63
- [Mergekit](https://github.com/arcee-ai/mergekit) configurations are YAML documents specifying the operations to perform in order to produce your merged model.
64
- Below are the primary elements of a configuration file:
65
-
66
- - `merge_method`: Specifies the method to use for merging models. See [Merge Methods](https://github.com/arcee-ai/mergekit#merge-methods) for a list.
67
- - `slices`: Defines slices of layers from different models to be used. This field is mutually exclusive with `models`.
68
- - `models`: Defines entire models to be used for merging. This field is mutually exclusive with `slices`.
69
- - `base_model`: Specifies the base model used in some merging methods.
70
- - `parameters`: Holds various parameters such as weights and densities, which can also be specified at different levels of the configuration.
71
- - `dtype`: Specifies the data type used for the merging operation.
72
- - `tokenizer_source`: Determines how to construct a tokenizer for the merged model.
73
-
74
- ## Merge Methods
75
-
76
- A quick overview of the currently supported merge methods:
77
-
78
- | Method | `merge_method` value | Multi-Model | Uses base model |
79
- | -------------------------------------------------------------------------------------------- | -------------------- | ----------- | --------------- |
80
- | Linear ([Model Soups](https://arxiv.org/abs/2203.05482)) | `linear` | โœ… | โŒ |
81
- | SLERP | `slerp` | โŒ | โœ… |
82
- | [Task Arithmetic](https://arxiv.org/abs/2212.04089) | `task_arithmetic` | โœ… | โœ… |
83
- | [TIES](https://arxiv.org/abs/2306.01708) | `ties` | โœ… | โœ… |
84
- | [DARE](https://arxiv.org/abs/2311.03099) [TIES](https://arxiv.org/abs/2306.01708) | `dare_ties` | โœ… | โœ… |
85
- | [DARE](https://arxiv.org/abs/2311.03099) [Task Arithmetic](https://arxiv.org/abs/2212.04089) | `dare_linear` | โœ… | โœ… |
86
- | Passthrough | `passthrough` | โŒ | โŒ |
87
- | [Model Stock](https://arxiv.org/abs/2403.19522) | `model_stock` | โœ… | โœ… |
88
-
89
-
90
- ## Citation
91
-
92
- This GUI is powered by [Arcee's MergeKit](https://arxiv.org/abs/2403.13257).
93
- If you use it in your research, please cite the following paper:
94
-
95
- ```
96
- @article{goddard2024arcee,
97
- title={Arcee's MergeKit: A Toolkit for Merging Large Language Models},
98
- author={Goddard, Charles and Siriwardhana, Shamane and Ehghaghi, Malikeh and Meyers, Luke and Karpukhin, Vlad and Benedict, Brian and McQuade, Mark and Solawetz, Jacob},
99
- journal={arXiv preprint arXiv:2403.13257},
100
- year={2024}
101
- }
102
- ```
103
-
104
- This Space is heavily inspired by LazyMergeKit by Maxime Labonne (see [Colab](https://colab.research.google.com/drive/1obulZ1ROXHjYLn6PPZJwRR6GzgQogxxb)).
105
- """
106
-
107
- examples = [[str(f)] for f in pathlib.Path("examples").glob("*.yaml")]
108
-
109
- # Do not set community token as `HF_TOKEN` to avoid accidentally using it in merge scripts.
110
- # `COMMUNITY_HF_TOKEN` is used to upload models to the community organization (https://huggingface.co/mergekit-community)
111
- # when user do not provide a token.
112
- COMMUNITY_HF_TOKEN = os.getenv("COMMUNITY_HF_TOKEN")
113
-
114
-
115
- def merge(yaml_config: str, hf_token: str, repo_name: str) -> Iterable[List[Log]]:
116
- runner = LogsViewRunner()
117
-
118
- if not yaml_config:
119
- yield runner.log("Empty yaml, pick an example below", level="ERROR")
120
- return
121
- try:
122
- merge_config = MergeConfiguration.model_validate(yaml.safe_load(yaml_config))
123
- except Exception as e:
124
- yield runner.log(f"Invalid yaml {e}", level="ERROR")
125
- return
126
-
127
- is_community_model = False
128
- if not hf_token:
129
- if "/" in repo_name and not repo_name.startswith("mergekit-community/"):
130
- yield runner.log(
131
- f"Cannot upload merge model to namespace {repo_name.split('/')[0]}: you must provide a valid token.",
132
- level="ERROR",
133
- )
134
- return
135
- yield runner.log(
136
- "No HF token provided. Your merged model will be uploaded to the https://huggingface.co/mergekit-community organization."
137
- )
138
- is_community_model = True
139
- if not COMMUNITY_HF_TOKEN:
140
- raise gr.Error("Cannot upload to community org: community token not set by Space owner.")
141
- hf_token = COMMUNITY_HF_TOKEN
142
-
143
- api = huggingface_hub.HfApi(token=hf_token)
144
-
145
- with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
146
- tmpdir = pathlib.Path(tmpdirname)
147
- merged_path = tmpdir / "merged"
148
- merged_path.mkdir(parents=True, exist_ok=True)
149
- config_path = merged_path / "config.yaml"
150
- config_path.write_text(yaml_config)
151
- yield runner.log(f"Merge configuration saved in {config_path}")
152
-
153
- if not repo_name:
154
- yield runner.log("No repo name provided. Generating a random one.")
155
- repo_name = f"mergekit-{merge_config.merge_method}"
156
- # Make repo_name "unique" (no need to be extra careful on uniqueness)
157
- repo_name += "-" + "".join(random.choices(string.ascii_lowercase, k=7))
158
- repo_name = repo_name.replace("/", "-").strip("-")
159
-
160
- if is_community_model and not repo_name.startswith("mergekit-community/"):
161
- repo_name = f"mergekit-community/{repo_name}"
162
-
163
- try:
164
- yield runner.log(f"Creating repo {repo_name}")
165
- repo_url = api.create_repo(repo_name, exist_ok=True)
166
- yield runner.log(f"Repo created: {repo_url}")
167
- except Exception as e:
168
- yield runner.log(f"Error creating repo {e}", level="ERROR")
169
- return
170
-
171
- # Set tmp HF_HOME to avoid filling up disk Space
172
- tmp_env = os.environ.copy() # taken from https://stackoverflow.com/a/4453495
173
- tmp_env["HF_HOME"] = f"{tmpdirname}/.cache"
174
- yield from runner.run_command(cli.split(), cwd=merged_path, env=tmp_env)
175
-
176
- if runner.exit_code != 0:
177
- yield runner.log("Merge failed. Deleting repo as no model is uploaded.", level="ERROR")
178
- api.delete_repo(repo_url.repo_id)
179
- return
180
-
181
- yield runner.log("Model merged successfully. Uploading to HF.")
182
- yield from runner.run_python(
183
- api.upload_folder,
184
- repo_id=repo_url.repo_id,
185
- folder_path=merged_path / "merge",
186
- )
187
- yield runner.log(f"Model successfully uploaded to HF: {repo_url.repo_id}")
188
-
189
- with gr.Blocks() as demo:
190
- with gr.Row():
191
- filename = gr.Textbox(visible=False, label="filename")
192
- config = gr.Code(language="yaml", lines=10, label="config.yaml")
193
- with gr.Column():
194
- token = gr.Textbox(
195
- lines=1,
196
- label="HF Write Token",
197
- info="https://hf.co/settings/token",
198
- type="password",
199
- placeholder="Optional. Will upload merged model to MergeKit Community if empty.",
200
- )
201
- repo_name = gr.Textbox(
202
- lines=1,
203
- label="Repo name",
204
- placeholder="Optional. Will create a random name if empty.",
205
- )
206
- repo_name.value = "Andrewstivan/AURA"
207
-
208
- # ะฃัั‚ะฐะฝะฐะฒะปะธะฒะฐะตะผ ะบะพะฝั„ะธะณ ะฟะพ ัƒะผะพะปั‡ะฐะฝะธัŽ (ัั‚ะพ ั‚ะพะถะต ะดะพะปะถะฝะพ ะฑั‹ั‚ัŒ ะฒะฝัƒั‚ั€ะธ demo, ะฝะพ ะฝะต ะฒะฝัƒั‚ั€ะธ Row)
209
- config.value = """slices:
210
  - sources:
211
  - model: ResplendentAI/Aura_v3_7B
212
  layer_range: [0, 32]
@@ -224,33 +25,35 @@ parameters:
224
  dtype: bfloat16
225
  tokenizer_source: union
226
  """
 
227
 
228
- button = gr.Button("Merge", variant="primary")
229
- logs = LogsView(label="Terminal output")
230
- gr.Examples(
231
- examples,
232
- fn=lambda s: (s,),
233
- run_on_click=True,
234
- label="Examples",
235
- inputs=[filename],
236
- outputs=[config],
237
- )
238
- gr.Markdown(MARKDOWN_ARTICLE)
239
- button.click(fn=merge, inputs=[config, token, repo_name], outputs=[logs])
240
-
241
- # Run garbage collection
242
- def _garbage_collect_every_hour():
243
- while True:
244
- try:
245
- garbage_collect_empty_models(token=COMMUNITY_HF_TOKEN)
246
- except Exception as e:
247
- print("Error running garbage collection", e)
248
- time.sleep(3600)
249
-
250
- pool = ThreadPoolExecutor()
251
- pool.submit(_garbage_collect_every_hour)
252
 
253
- # ะะฒั‚ะพะทะฐะฟัƒัะบ ัะปะธัะฝะธั
254
- threading.Thread(target=lambda: merge(config.value, token.value, repo_name.value), daemon=True).start()
255
 
256
- demo.queue(default_concurrency_limit=1).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
 
 
 
2
  import tempfile
3
+ import subprocess
4
+ from huggingface_hub import login, HfApi
 
 
5
 
6
+ # === ะะะกะขะ ะžะ™ะšะ˜ ===
7
+ REPO_NAME = "Andrewstivan/AURA"
8
+ HF_TOKEN = os.getenv("HF_TOKEN")
 
 
 
9
 
10
+ YAML_CONFIG = """slices:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  - sources:
12
  - model: ResplendentAI/Aura_v3_7B
13
  layer_range: [0, 32]
 
25
  dtype: bfloat16
26
  tokenizer_source: union
27
  """
28
+ # ===================
29
 
30
+ if not HF_TOKEN:
31
+ raise Exception("โŒ HF_TOKEN not found. Add it in Settings โ†’ Variables and secrets")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ print("๐Ÿ”„ Starting merge...")
34
+ login(token=HF_TOKEN)
35
 
36
+ with tempfile.TemporaryDirectory() as tmpdir:
37
+ config_path = f"{tmpdir}/config.yaml"
38
+ with open(config_path, "w") as f:
39
+ f.write(YAML_CONFIG)
40
+
41
+ merged_path = f"{tmpdir}/merged"
42
+ os.makedirs(merged_path, exist_ok=True)
43
+
44
+ cmd = f"mergekit-yaml {config_path} {merged_path} --copy-tokenizer --allow-crimes --out-shard-size 1B"
45
+
46
+ process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
47
+ for line in iter(process.stdout.readline, ''):
48
+ print(line, end='')
49
+
50
+ process.wait()
51
+
52
+ if process.returncode == 0:
53
+ print("โœ… Merge complete! Uploading...")
54
+ api = HfApi()
55
+ api.create_repo(REPO_NAME, exist_ok=True)
56
+ api.upload_folder(folder_path=merged_path, repo_id=REPO_NAME, repo_type="model")
57
+ print(f"๐ŸŽ‰ Done! https://huggingface.co/{REPO_NAME}")
58
+ else:
59
+ print(f"โŒ Error: {process.returncode}")