Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

setup-runner.py 11 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
  1. import importlib
  2. import fire
  3. import yaml
  4. import logging
  5. import os
  6. import sys
  7. from pathlib import Path
  8. from addict import Dict
  9. import json
  10. import time
  11. import runpod
  12. from datetime import datetime, timezone, timedelta
  13. import signal
  14. from tqdm import tqdm
  15. import re
  16. from discord import SyncWebhook
  17. import pexpect
  18. AXOLOTL_RUNPOD_IMAGE = 'winglian/axolotl-runpod:main-py3.10-cu118-2.0.1'
  19. AXOLOTL_RUNPOD_IMAGE_SIZE_IN_GB = 12.5
  20. AXOLOTL_RUNPOD_IMAGE_SIZE = AXOLOTL_RUNPOD_IMAGE_SIZE_IN_GB * 1024 # In MB
  21. BITS_PER_BYTE = 8
  22. COMPRESSION_RATIO = 0.2
  23. DEFAULT_TEMPLATE_ID = '758uq6u5fc'
  24. MAX_BID_PER_GPU = 2.0
  25. POLL_PERIOD = 5 # 5 seconds
  26. MAX_WAIT_TIME = 60 * 10 # 10 minutes
  27. DEFAULT_STOP_AFTER = 60 * 15 # 15 minutes to prevent accidental starting a pod and forgot to stop
  28. DEFAULT_TERMINATE_AFTER = 60 * 60 * 24 # 24 hours to prevent accidental starting a pod and forgot to terminate
  29. class DictDefault(Dict):
  30. """
  31. A Dict that returns None instead of returning empty Dict for missing keys.
  32. Borrowed from https://github.com/utensil/axolotl/blob/local_dataset/src/axolotl/utils/dict.py
  33. """
  34. def __missing__(self, key):
  35. return None
  36. project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
  37. os.chdir(project_root)
  38. # src_dir = os.path.join(project_root, "src")
  39. # sys.path.insert(0, src_dir)
  40. logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
  41. # os.environ["RUNPOD_DEBUG"] = 'true'
  42. def notify_discord(msg):
  43. webhook = SyncWebhook.from_url(os.getenv("DISCORD_WEBHOOK_URL"))
  44. return webhook.send(msg, wait=True)
  45. def edit_discord_message(last_msg, msg):
  46. return last_msg.edit(content=msg)
  47. def log_info(msg):
  48. logging.info(msg)
  49. return notify_discord(msg)
  50. def log_error(msg, exc_info=None):
  51. logging.error(msg, exc_info=exc_info)
  52. if exc_info is not None:
  53. return notify_discord(f'{msg}: {exc_info}')
  54. else:
  55. return notify_discord(msg)
  56. def as_yaml(data):
  57. return f'```yaml\n{yaml.dump(data, allow_unicode=True)}\n```'
  58. def terminate(pod):
  59. runpod.terminate_pod(pod['id'])
  60. log_info(f"Pod {pod['id']} terminated")
  61. def train_on_runpod(
  62. config,
  63. **kwargs,
  64. ):
  65. config = Path(config.strip())
  66. log_info(f"Setting up RunPod with config: {config}")
  67. pexpect.run('gh workflow enable monit.yml')
  68. # load the config from the yaml file
  69. # Mostly borrowed from https://github.com/utensil/axolotl/blob/local_dataset/scripts/finetune.py
  70. with open(config, encoding="utf-8") as file:
  71. cfg: DictDefault = DictDefault(yaml.safe_load(file))
  72. # if there are any options passed in the cli, if it is something that seems valid from the yaml,
  73. # then overwrite the value
  74. cfg_keys = cfg.keys()
  75. for k, _ in kwargs.items():
  76. # if not strict, allow writing to cfg even if it's not in the yml already
  77. if k in cfg_keys or not cfg.strict:
  78. # handle booleans
  79. if isinstance(cfg[k], bool):
  80. cfg[k] = bool(kwargs[k])
  81. else:
  82. cfg[k] = kwargs[k]
  83. # get the runpod config
  84. runpod_cfg = cfg.pop('runpod', None)
  85. if runpod_cfg is None:
  86. raise ValueError("No pod config found in config file")
  87. runpod_api_key = os.getenv("RUNPOD_API_KEY")
  88. if runpod_api_key is None:
  89. raise ValueError("No RUNPOD_API_KEY environment variable found")
  90. runpod.api_key = runpod_api_key
  91. gpu = runpod_cfg.gpu or "NVIDIA RTX A5000"
  92. gpu_info = runpod.get_gpu(gpu)
  93. logging.info(f"GPU Info: {gpu_info}")
  94. # TODO: warn if the bid is too high
  95. bid_per_gpu = min(gpu_info['lowestPrice']['minimumBidPrice'] or MAX_BID_PER_GPU, runpod_cfg.max_bid_per_gpu or MAX_BID_PER_GPU)
  96. env = runpod_cfg.env or {}
  97. env['TRAINING_CONFIG'] = str(config)
  98. env['AXOLOTL_GIT'] = runpod_cfg.axolotl_git or 'https://github.com/OpenAccess-AI-Collective/axolotl'
  99. env['AXOLOTL_GIT_BRANCH'] = runpod_cfg.axolotl_git_branch or 'main'
  100. env['AXOLOTL_ROOT'] = runpod_cfg.axolotl_root or '/workspace/axolotl'
  101. env['DISCORD_WEBHOOK_URL'] = os.getenv("DISCORD_WEBHOOK_URL")
  102. env['PREDOWNLOAD_MODEL'] = cfg.base_model
  103. deepspeed = runpod_cfg.deepspeed or cfg.deepspeed or False
  104. if deepspeed:
  105. if str(deepspeed).lower() == 'true':
  106. deepspeed = config.parent.joinpath('./ds_config.json')
  107. else:
  108. deepspeed = config.parent.joinpath(deepspeed)
  109. env['ACCELERATE_USE_DEEPSPEED'] = 'true'
  110. env['DEEPSPEED_CONFIG_PATH'] = deepspeed
  111. log_info(f"Deepspeed enabled, using config: {deepspeed}")
  112. entry = None
  113. if runpod_cfg.entry is not None:
  114. # TODO: find a better way to escape the entry
  115. entry = json.dumps(runpod_cfg.entry)[1:-1]
  116. if runpod_cfg.stop_after == -1:
  117. stop_after = None
  118. else:
  119. stop_after = (datetime.now(timezone.utc) + timedelta(seconds=runpod_cfg.stop_after or DEFAULT_STOP_AFTER)).strftime('"%Y-%m-%dT%H:%M:%SZ"')
  120. if runpod_cfg.terminate_after == -1:
  121. terminate_after = None
  122. else:
  123. terminate_after = (datetime.now(timezone.utc) + timedelta(seconds=runpod_cfg.terminate_after or DEFAULT_TERMINATE_AFTER)).strftime('"%Y-%m-%dT%H:%M:%SZ"')
  124. if runpod_cfg.debug:
  125. os.environ["RUNPOD_DEBUG"] = 'true'
  126. logging.info(f"Debug mode enabled")
  127. try:
  128. if runpod_cfg.pod_type == 'INTERRUPTABLE':
  129. pod = runpod.create_spot_pod(f'Training {config}',
  130. AXOLOTL_RUNPOD_IMAGE,
  131. gpu,
  132. cloud_type=runpod_cfg.cloud_type or "SECURE",
  133. bid_per_gpu=bid_per_gpu,
  134. template_id=runpod_cfg.template_id or DEFAULT_TEMPLATE_ID,
  135. volume_mount_path=runpod_cfg.volume_mount_path or '/content',
  136. container_disk_in_gb=runpod_cfg.container_disk_in_gb or 50,
  137. volume_in_gb=runpod_cfg.volume_in_gb or 200,
  138. gpu_count=runpod_cfg.gpu_count or 1,
  139. min_vcpu_count=runpod_cfg.min_vcpu_count or 8,
  140. min_memory_in_gb=runpod_cfg.min_memory_in_gb or 29,
  141. min_download=runpod_cfg.min_download or None,
  142. min_upload=runpod_cfg.min_upload or None,
  143. docker_args=entry,
  144. env=env,
  145. stop_after=stop_after,
  146. terminate_after=terminate_after
  147. )
  148. else:
  149. pod = runpod.create_pod(f'Training {config}',
  150. AXOLOTL_RUNPOD_IMAGE,
  151. gpu,
  152. cloud_type=runpod_cfg.cloud_type or "SECURE",
  153. template_id=runpod_cfg.template_id or DEFAULT_TEMPLATE_ID,
  154. volume_mount_path=runpod_cfg.volume_mount_path or '/content',
  155. container_disk_in_gb=runpod_cfg.container_disk_in_gb or 50,
  156. volume_in_gb=runpod_cfg.volume_in_gb or 200,
  157. gpu_count=runpod_cfg.gpu_count or 1,
  158. min_vcpu_count=runpod_cfg.min_vcpu_count or 8,
  159. min_memory_in_gb=runpod_cfg.min_memory_in_gb or 29,
  160. min_download=runpod_cfg.min_download or None,
  161. min_upload=runpod_cfg.min_upload or None,
  162. docker_args=entry,
  163. env=env,
  164. stop_after=stop_after,
  165. terminate_after=terminate_after
  166. )
  167. except Exception as ex:
  168. log_error(f"Failed to create pod for {config}", exc_info=ex)
  169. sys.exit(0)
  170. if pod is None:
  171. log_error(f"Failed to create pod for {config}")
  172. return
  173. def signal_handler(signal, frame):
  174. logging.info(f"Keyboard interrupt received, terminating pod {pod['id']}")
  175. terminate(pod)
  176. sys.exit(0)
  177. signal.signal(signal.SIGINT, signal_handler)
  178. msg_created = log_info(f"Created pod {pod['id']}, waiting for it to start...(at most {MAX_WAIT_TIME} seconds)")
  179. username = pod['machine']['podHostId']
  180. ssh_command = f'ssh {username}@ssh.runpod.io -i ~/.ssh/id_ed25519'
  181. codespace_ssh_command = f'username={username} scripts/ssh_runpod.sh'
  182. try:
  183. # wait for the pod to start
  184. pod_info = runpod.get_pod(pod['id'])['pod']
  185. logging.info(f"More about the pod {pod['id']}: {pod_info}")
  186. eta = AXOLOTL_RUNPOD_IMAGE_SIZE * BITS_PER_BYTE / pod_info['machine']['maxDownloadSpeedMbps'] + AXOLOTL_RUNPOD_IMAGE_SIZE / COMPRESSION_RATIO / pod_info['machine']['diskMBps']
  187. logging.info(f" - Estimated time to download and extrace the image: {eta} seconds")
  188. logging.info(f" - While you're waiting, you can check the status of the pod at https://www.runpod.io/console/pods ")
  189. logging.info(f" - After started, use the following command to ssh into the pod: {ssh_command}")
  190. logging.info(f" or the following command in CodeSpace: {codespace_ssh_command}")
  191. runtime = None
  192. waited_time = 0
  193. is_debug = os.getenv("RUNPOD_DEBUG") or ''
  194. os.environ["RUNPOD_DEBUG"] = ''
  195. with tqdm(total=eta) as pbar:
  196. while runtime is None and waited_time < MAX_WAIT_TIME:
  197. pod_info = runpod.get_pod(pod['id'])['pod']
  198. runtime = pod_info['runtime']
  199. time.sleep(POLL_PERIOD)
  200. waited_time += POLL_PERIOD
  201. pbar.update(POLL_PERIOD)
  202. edit_discord_message(msg_created, f"Created pod {pod['id']}, waited for {waited_time}/{eta:.2f} seconds...")
  203. os.environ["RUNPOD_DEBUG"] = is_debug
  204. if runtime is None:
  205. log_error(f"Pod {pod['id']} failed to start in {MAX_WAIT_TIME} seconds: {pod_info}")
  206. terminate(pod)
  207. logging.info(f"Pod {pod['id']} started:\n{as_yaml(pod_info)}")
  208. edit_discord_message(msg_created, f"Pod {pod['id']} started:\n{as_yaml(pod_info)}")
  209. # myself = runpod.get_myself()
  210. # log_info(f"RunPod overview:\n{as_yaml(myself)}")
  211. except Exception as ex:
  212. log_error(f"Something went wrong with {pod['id']}", exc_info=ex)
  213. terminate(pod)
  214. if __name__ == "__main__":
  215. fire.Fire(train_on_runpod)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...