solveit-modal 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
@@ -0,0 +1,43 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/solveit-modal',
5
+ 'doc_host': 'https://ForBo7.github.io',
6
+ 'git_url': 'https://github.com/ForBo7/solveit-modal',
7
+ 'lib_path': 'solveit_modal'},
8
+ 'syms': { 'solveit_modal.core': { 'solveit_modal.core.gpu_off': ('core.html#gpu_off', 'solveit_modal/core.py'),
9
+ 'solveit_modal.core.gpu_on': ('core.html#gpu_on', 'solveit_modal/core.py'),
10
+ 'solveit_modal.core.link_remote_kernel': ('core.html#link_remote_kernel', 'solveit_modal/core.py'),
11
+ 'solveit_modal.core.provision_sandbox': ('core.html#provision_sandbox', 'solveit_modal/core.py'),
12
+ 'solveit_modal.core.setup_ssh': ('core.html#setup_ssh', 'solveit_modal/core.py')},
13
+ 'solveit_modal.gpu': { 'solveit_modal.gpu.GPU': ('gpu.html#gpu', 'solveit_modal/gpu.py'),
14
+ 'solveit_modal.gpu.GPU.__repr__': ('gpu.html#gpu.__repr__', 'solveit_modal/gpu.py'),
15
+ 'solveit_modal.gpu.GPU._repr_html_': ('gpu.html#gpu._repr_html_', 'solveit_modal/gpu.py'),
16
+ 'solveit_modal.gpu.GPU.by_budget': ('gpu.html#gpu.by_budget', 'solveit_modal/gpu.py'),
17
+ 'solveit_modal.gpu.GPU.by_vram': ('gpu.html#gpu.by_vram', 'solveit_modal/gpu.py'),
18
+ 'solveit_modal.gpu.GPU.cheapest': ('gpu.html#gpu.cheapest', 'solveit_modal/gpu.py'),
19
+ 'solveit_modal.gpu.GPU.most_expensive': ('gpu.html#gpu.most_expensive', 'solveit_modal/gpu.py'),
20
+ 'solveit_modal.gpu.GPU.price_of': ('gpu.html#gpu.price_of', 'solveit_modal/gpu.py'),
21
+ 'solveit_modal.gpu.GPU.tags': ('gpu.html#gpu.tags', 'solveit_modal/gpu.py'),
22
+ 'solveit_modal.gpu.GPUEntry': ('gpu.html#gpuentry', 'solveit_modal/gpu.py'),
23
+ 'solveit_modal.gpu.GPUEntry.__init__': ('gpu.html#gpuentry.__init__', 'solveit_modal/gpu.py'),
24
+ 'solveit_modal.gpu.GPUEntry.__repr__': ('gpu.html#gpuentry.__repr__', 'solveit_modal/gpu.py'),
25
+ 'solveit_modal.gpu.GPUEntry._repr_html_': ('gpu.html#gpuentry._repr_html_', 'solveit_modal/gpu.py')},
26
+ 'solveit_modal.kernel': { 'solveit_modal.kernel.get_remote_python': ( 'ipyfernel.html#get_remote_python',
27
+ 'solveit_modal/kernel.py'),
28
+ 'solveit_modal.kernel.start_remote_kernel': ( 'ipyfernel.html#start_remote_kernel',
29
+ 'solveit_modal/kernel.py')},
30
+ 'solveit_modal.sandbox': { 'solveit_modal.sandbox.get_apts': ('sandbox.html#get_apts', 'solveit_modal/sandbox.py'),
31
+ 'solveit_modal.sandbox.get_pips': ('sandbox.html#get_pips', 'solveit_modal/sandbox.py'),
32
+ 'solveit_modal.sandbox.get_pubkey': ('sandbox.html#get_pubkey', 'solveit_modal/sandbox.py'),
33
+ 'solveit_modal.sandbox.get_secrets': ('sandbox.html#get_secrets', 'solveit_modal/sandbox.py'),
34
+ 'solveit_modal.sandbox.get_tunnel': ('sandbox.html#get_tunnel', 'solveit_modal/sandbox.py'),
35
+ 'solveit_modal.sandbox.in_modal': ('sandbox.html#in_modal', 'solveit_modal/sandbox.py'),
36
+ 'solveit_modal.sandbox.in_solveit': ('sandbox.html#in_solveit', 'solveit_modal/sandbox.py'),
37
+ 'solveit_modal.sandbox.inject_pubkey': ('sandbox.html#inject_pubkey', 'solveit_modal/sandbox.py'),
38
+ 'solveit_modal.sandbox.mk_app': ('sandbox.html#mk_app', 'solveit_modal/sandbox.py'),
39
+ 'solveit_modal.sandbox.mk_img': ('sandbox.html#mk_img', 'solveit_modal/sandbox.py'),
40
+ 'solveit_modal.sandbox.mk_sandbox': ('sandbox.html#mk_sandbox', 'solveit_modal/sandbox.py'),
41
+ 'solveit_modal.sandbox.mk_ssh': ('sandbox.html#mk_ssh', 'solveit_modal/sandbox.py'),
42
+ 'solveit_modal.sandbox.start_ssh': ('sandbox.html#start_ssh', 'solveit_modal/sandbox.py'),
43
+ 'solveit_modal.sandbox.verify_ssh': ('sandbox.html#verify_ssh', 'solveit_modal/sandbox.py')}}}
solveit_modal/core.py ADDED
@@ -0,0 +1,97 @@
1
+ """Add/remove a GPU to/from your SolveIt instance in one function.
2
+
3
+ Docs: https://ForBo7.github.io/solveit-modalcore.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['log', 'provision_sandbox', 'setup_ssh', 'link_remote_kernel', 'gpu_on', 'gpu_off', 'connect_existing_kernel', 'gip',
9
+ 'ipf_exec', 'ipf_shutdown', 'ipf_startup', 'local', 'register_remote_kernel', 'remote', 'set_ssh_config',
10
+ 'set_sticky', 'start_remote', 'stop_remote', 'unset_sticky']
11
+
12
+ # %% ../nbs/00_core.ipynb #23c76ec0
13
+ from .sandbox import *
14
+ from .kernel import *
15
+
16
+ # %% ../nbs/00_core.ipynb #3f7d798d
17
+ from ipyfernel.core import *
18
+
19
+ # %% ../nbs/00_core.ipynb #3330ffa2
20
+ _all_ = ['connect_existing_kernel', 'gip', 'ipf_exec', 'ipf_shutdown', 'ipf_startup',
21
+ 'local', 'register_remote_kernel', 'remote', 'set_ssh_config',
22
+ 'set_sticky', 'start_remote', 'stop_remote', 'unset_sticky']
23
+
24
+ # %% ../nbs/00_core.ipynb #8f64a7c2
25
+ def provision_sandbox(
26
+ gpu:str, # GPU type string, e.g. 'T4', 'A100'
27
+ timeout:int # Max sandbox lifetime in seconds
28
+ ) -> tuple: # (sandbox, host, port)
29
+ "Create Modal app, image, sandbox, and expose TCP tunnel."
30
+ app = mk_app()
31
+ img = mk_img()
32
+ sb = mk_sandbox(app, img, gpu=gpu, timeout=timeout)
33
+ host, port = get_tunnel(sb)
34
+ return sb, host, port
35
+
36
+ # %% ../nbs/00_core.ipynb #a2ad70d1
37
+ import modal
38
+
39
+ # %% ../nbs/00_core.ipynb #f77b6d0a
40
+ def setup_ssh(
41
+ sb :modal.sandbox.Sandbox, # Modal Sandbox object
42
+ host:str, # Tunnel hostname
43
+ port:int # Tunnel port
44
+ ) -> object: # Paramiko SSH connection
45
+ "Inject public key, start SSH service, and verify connectivity."
46
+ inject_pubkey(sb, get_pubkey())
47
+ start_ssh(sb)
48
+ ssh = mk_ssh(host, port)
49
+ verify_ssh(ssh)
50
+ return ssh
51
+
52
+ # %% ../nbs/00_core.ipynb #92f8c6c7
53
+ import logging
54
+
55
+ # %% ../nbs/00_core.ipynb #f7d90970
56
+ logging.basicConfig(level=logging.INFO, format='%(message)s - %(levelname)s | %(asctime)s')
57
+ log = logging.getLogger(__name__)
58
+
59
+ # %% ../nbs/00_core.ipynb #c756caba
60
+ def link_remote_kernel(
61
+ ssh :object, # Paramiko SSH connection
62
+ host :str, # Tunnel hostname
63
+ port :int, # Tunnel port
64
+ sticky:bool=False # Set `True` to execute code remotely by default
65
+ ):
66
+ "Launch remote IPython kernel on sandbox and connect ipyfernel to it."
67
+ start_remote_kernel(ssh)
68
+ p = get_remote_python(ssh)
69
+ register_remote_kernel(remote_python=p)
70
+ connect_existing_kernel(f'{host}:{port}')
71
+ log.info('✔ connected to remote kernel')
72
+ if sticky:
73
+ set_sticky()
74
+ log.warning('! code now runs remotely by default; run `%local unset_sticky()` to run code locally')
75
+ log.warning('! remote kernel environment has a different set of libraries installed')
76
+
77
+ # %% ../nbs/00_core.ipynb #f2fd6ed6
78
+ def gpu_on(
79
+ gpu='T4', # GPU type string
80
+ timeout=1800 # Max sandbox lifetime in seconds
81
+ ) -> tuple: # (sandbox, ssh)
82
+ "Provision a GPU sandbox, wire up SSH, and hijack cells onto a remote kernel."
83
+ sb, host, port = provision_sandbox(gpu, timeout)
84
+ ssh = setup_ssh(sb, host, port)
85
+ link_remote_kernel(ssh, host, port)
86
+ return sb, ssh
87
+
88
+ # %% ../nbs/00_core.ipynb #7d2d9bae
89
+ def gpu_off(
90
+ sb:modal.sandbox.Sandbox # sandbox object from gpu_on
91
+ ):
92
+ "Restore local kernel, disconnect remote, and teardown sandbox. Must be called from a %%local cell."
93
+ unset_sticky()
94
+ stop_remote()
95
+ log.info('✔ unlinked from remote kernel')
96
+ sb.terminate()
97
+ log.info('✔ terminated sandbox')
solveit_modal/gpu.py ADDED
@@ -0,0 +1,110 @@
1
+ """Explore GPUs available on Modal
2
+
3
+ Docs: https://ForBo7.github.io/solveit-modalgpu.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_gpu.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['GPUEntry', 'GPU']
9
+
10
+ # %% ../nbs/03_gpu.ipynb #6d5e354e
11
+ class GPUEntry:
12
+ def __init__(self,
13
+ tag:str, # GPU tag, e.g. 'H100'
14
+ price:float, # Price per hour (USD)
15
+ vram:int, # VRAM in GB
16
+ ) -> None: store_attr()
17
+ def __repr__(self) -> str: return f'{self.tag} — ${self.price:.2f}/hr, {self.vram}GB'
18
+ def _repr_html_(self) -> str: return f'<div style="background:#e8f4e8;padding:8px 12px;border-radius:6px;display:inline-block;font-family:monospace"><b>{self.tag}</b> · ${self.price:.2f}/hr · {self.vram}GB</div>'
19
+
20
+
21
+ # %% ../nbs/03_gpu.ipynb #e4fbc570
22
+ from datetime import date
23
+
24
+ # %% ../nbs/03_gpu.ipynb #52795829
25
+ from fastcore.all import *
26
+
27
+ # %% ../nbs/03_gpu.ipynb #b0304fde
28
+ class GPU:
29
+ _source = 'https://modal.com/pricing'
30
+ _updated = date(2026, 5, 22)
31
+
32
+ T4 = GPUEntry('T4', 0.59, 16)
33
+ L4 = GPUEntry('L4', 0.80, 24)
34
+ A10 = GPUEntry('A10', 1.10, 24)
35
+ L40S = GPUEntry('L40S', 1.95, 48)
36
+ A100_40GB = GPUEntry('A100-40GB', 2.10, 40)
37
+ A100_80GB = GPUEntry('A100-80GB', 2.50, 80)
38
+ RTX_PRO_6000 = GPUEntry('RTX-PRO-6000', 3.03, 96)
39
+ H100 = GPUEntry('H100', 3.95, 80)
40
+ H200 = GPUEntry('H200', 4.54, 141)
41
+ B200 = GPUEntry('B200', 6.25, 180)
42
+
43
+ def __repr__(self) -> str:
44
+ lines = [f'GPU variants (as of {self._updated}, from {self._source}):']
45
+ for _, v in sorted(self.__class__.__dict__.items()):
46
+ if isinstance(v, GPUEntry): lines.append(f' {v.tag:<15} ${v.price:.2f}/hr {v.vram:>3}GB')
47
+ return '\n'.join(lines)
48
+
49
+ def _repr_html_(self) -> str:
50
+ entries = sorted((v for _,v in self.__class__.__dict__.items() if isinstance(v,GPUEntry)), key=lambda e:e.price)
51
+ return '<div style="display:flex;flex-wrap:wrap;gap:8px">' + ''.join(e._repr_html_() for e in entries) + '</div>'
52
+
53
+
54
+ # %% ../nbs/03_gpu.ipynb #57a69cc7
55
+ from fastcore.all import *
56
+
57
+ # %% ../nbs/03_gpu.ipynb #ee7c12b9
58
+ @patch
59
+ def cheapest(self:GPU) -> GPUEntry:
60
+ "Return the cheapest GPUEntry."
61
+ return min((v for _,v in self.__class__.__dict__.items() if isinstance(v,GPUEntry)), key=lambda x: x.price)
62
+
63
+
64
+ # %% ../nbs/03_gpu.ipynb #dced5eca
65
+ from IPython.display import HTML
66
+
67
+ # %% ../nbs/03_gpu.ipynb #1d05e561
68
+ @patch
69
+ def by_budget(self:GPU,
70
+ max_phr:float, # Maximum price per hour
71
+ ) -> HTML:
72
+ "Return GPU cards costing ≤ `max_phr` per hour as HTML."
73
+ entries = sorted((v for _,v in self.__class__.__dict__.items() if isinstance(v,GPUEntry) and v.price <= max_phr), key=lambda e:e.price)
74
+ return HTML('<div style="display:flex;flex-wrap:wrap;gap:8px">' + ''.join(e._repr_html_() for e in entries) + '</div>')
75
+
76
+
77
+ # %% ../nbs/03_gpu.ipynb #f69fdb43
78
+ @patch
79
+ def price_of(self:GPU,
80
+ tag:str, # GPU tag, e.g. 'H100'
81
+ ) -> GPUEntry:
82
+ "Return the GPUEntry matching `tag`."
83
+ for _,v in self.__class__.__dict__.items():
84
+ if isinstance(v,GPUEntry) and v.tag==tag: return v
85
+ tags = [v.tag for _,v in self.__class__.__dict__.items() if isinstance(v,GPUEntry)]
86
+ raise KeyError(f'{tag} not found — available: {tags}')
87
+
88
+
89
+ # %% ../nbs/03_gpu.ipynb #849875a4
90
+ @patch
91
+ def tags(self:GPU) -> list[str]:
92
+ "Lists all available GPU tags"
93
+ return [v.tag for _,v in self.__class__.__dict__.items() if isinstance(v,GPUEntry)]
94
+
95
+ # %% ../nbs/03_gpu.ipynb #1d7e5218
96
+ @patch
97
+ def most_expensive(self:GPU) -> GPUEntry:
98
+ "Return the most expensive GPUEntry."
99
+ return max((v for _,v in self.__class__.__dict__.items() if isinstance(v,GPUEntry)), key=lambda x: x.price)
100
+
101
+
102
+ # %% ../nbs/03_gpu.ipynb #36b7e73c
103
+ @patch
104
+ def by_vram(self:GPU,
105
+ min_gb:int, # Minimum VRAM in GB
106
+ ) -> HTML:
107
+ "Return GPU cards with ≥ `min_gb` VRAM as HTML."
108
+ entries = sorted((v for _,v in self.__class__.__dict__.items() if isinstance(v,GPUEntry) and v.vram >= min_gb), key=lambda e:e.price)
109
+ return HTML('<div style="display:flex;flex-wrap:wrap;gap:8px">' + ''.join(e._repr_html_() for e in entries) + '</div>')
110
+
@@ -0,0 +1,54 @@
1
+ """Connecting a solveit kernel to a Modal sandbox
2
+
3
+ Docs: https://ForBo7.github.io/solveit-modalipyfernel.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_ipyfernel.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['log', 'start_remote_kernel', 'get_remote_python', 'connect_existing_kernel', 'gip', 'ipf_exec', 'ipf_shutdown',
9
+ 'ipf_startup', 'local', 'register_remote_kernel', 'remote', 'set_ssh_config', 'set_sticky', 'start_remote',
10
+ 'stop_remote', 'unset_sticky']
11
+
12
+ # %% ../nbs/02_ipyfernel.ipynb #0756ee20
13
+ import logging
14
+
15
+ # %% ../nbs/02_ipyfernel.ipynb #9b0da6bc
16
+ logging.basicConfig(level=logging.INFO, format='%(message)s - %(levelname)s | %(asctime)s')
17
+ log = logging.getLogger(__name__)
18
+
19
+ # %% ../nbs/02_ipyfernel.ipynb #c0e9b2f6
20
+ from time import sleep
21
+
22
+ # %% ../nbs/02_ipyfernel.ipynb #f21e4184
23
+ from typing import Callable
24
+
25
+ # %% ../nbs/02_ipyfernel.ipynb #24680f70
26
+ def start_remote_kernel(
27
+ ssh:Callable, # SSH caller from mk_ssh
28
+ kernel_path:str='/root/.local/share/jupyter/runtime/kernel-ipyf.json', # kernel JSON path
29
+ ):
30
+ "Start remote kernel and wait until ready."
31
+ log.info('∞ starting kernel')
32
+ ssh('mkdir', '-p', '/root/.local/share/jupyter/runtime')
33
+ ssh(f'nohup python3 -m ipykernel_launcher -f {kernel_path} >/tmp/kernel.log 2>&1 &')
34
+ for i in range(10):
35
+ if 'ok' in ssh(f'test -f {kernel_path} && echo ok || echo no'): break
36
+ sleep(0.2)
37
+ klog = ssh('cat /tmp/kernel.log')
38
+ assert 'To connect another client' in klog, f'kernel failed to start:\n{klog}'
39
+ log.info(f'✔ remote kernel ready: {kernel_path}')
40
+
41
+ # %% ../nbs/02_ipyfernel.ipynb #1f53ae0f
42
+ def get_remote_python(
43
+ ssh:Callable, # SSH caller from mk_ssh
44
+ ) -> str: # path to remote python
45
+ "Return the path of Python on the remote machine."
46
+ return ssh('which python3')
47
+
48
+ # %% ../nbs/02_ipyfernel.ipynb #6b35bcb8
49
+ from ipyfernel.core import *
50
+
51
+ # %% ../nbs/02_ipyfernel.ipynb #3e724f7d
52
+ _all_ = ['connect_existing_kernel', 'gip', 'ipf_exec', 'ipf_shutdown', 'ipf_startup',
53
+ 'local', 'register_remote_kernel', 'remote', 'set_ssh_config',
54
+ 'set_sticky', 'start_remote', 'stop_remote', 'unset_sticky']
@@ -0,0 +1,172 @@
1
+ """Abstractions for creating a Modal Sandbox, and interacting with it via SSH.
2
+
3
+ Docs: https://ForBo7.github.io/solveit-modalsandbox.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_sandbox.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['log', 'mk_app', 'mk_img', 'get_secrets', 'mk_sandbox', 'get_tunnel', 'get_pubkey', 'inject_pubkey', 'start_ssh',
9
+ 'mk_ssh', 'verify_ssh', 'get_apts', 'get_pips', 'in_modal', 'in_solveit']
10
+
11
+ # %% ../nbs/01_sandbox.ipynb #03380e24
12
+ import modal
13
+
14
+ # %% ../nbs/01_sandbox.ipynb #978005b2
15
+ def mk_app(
16
+ name:str='solveit-sandbox' # App name to look up or create
17
+ ) -> modal.App:
18
+ "Look up a Modal App by name, creating it if missing."
19
+ return modal.App.lookup(name, create_if_missing=True)
20
+
21
+ # %% ../nbs/01_sandbox.ipynb #433a2601
22
+ _default_pips = [
23
+ 'ipykernel',
24
+ 'fastai', 'transformers', 'diffusers', 'accelerate', 'datasets',
25
+ 'huggingface_hub', 'peft', 'safetensors', 'sentence-transformers',
26
+ 'xformers', 'bitsandbytes', 'ninja', 'einops',
27
+ 'wandb',
28
+ 'gradio', 'python-fasthtml', 'plotly', 'ipywidgets',
29
+ 'fsspec', 's3fs', 'gcsfs',
30
+ 'librosa', 'imageio', 'imageio-ffmpeg',
31
+ ]
32
+
33
+ # %% ../nbs/01_sandbox.ipynb #90830daf
34
+ def mk_img(
35
+ pips:list|None=None, # pip packages (defaults to _default_pips)
36
+ ) -> modal.Image:
37
+ "Create a Modal Image with system + Python packages."
38
+ if pips is None: pips = _default_pips
39
+ return modal.Image.debian_slim().apt_install('openssh-server').pip_install(pips)
40
+
41
+ # %% ../nbs/01_sandbox.ipynb #f7772c3a
42
+ import json
43
+
44
+ # %% ../nbs/01_sandbox.ipynb #4058df3e
45
+ def get_secrets() -> dict[str,str]:
46
+ "Secrets from solveit_settings.json."
47
+ with open('/app/data/solveit_settings.json') as f: return json.load(f)['secrets']
48
+
49
+ # %% ../nbs/01_sandbox.ipynb #f62a2560
50
+ import logging
51
+
52
+ # %% ../nbs/01_sandbox.ipynb #36d84cad
53
+ logging.basicConfig(level=logging.INFO, format='%(message)s - %(levelname)s | %(asctime)s')
54
+ log = logging.getLogger(__name__)
55
+
56
+ # %% ../nbs/01_sandbox.ipynb #2c02f113
57
+ def mk_sandbox(
58
+ app :modal.App, # Modal App to register the Sandbox with
59
+ img :modal.Image, # Image for the Sandbox environment
60
+ timeout:int =1800, # auto-terminate after this many seconds
61
+ gpu :str|None =None, # GPU type (e.g. "T4", "A100") or None
62
+ secrets:dict|None =None, # secrets dict (defaults to local solveit)
63
+ volumes:dict|None =None, # mount path → modal.Volume (defaults to /data solveit-volume)
64
+ ) -> modal.Sandbox:
65
+ "Create a Modal Sandbox with optional GPU, SSH, and Volumes."
66
+ if secrets is None: secrets = get_secrets() # <1>
67
+ if volumes is None: volumes = {"/data": modal.Volume.from_name("solveit-volume", create_if_missing=True)} # <2>
68
+ log.info('∞ creating sandbox; this may take 5-10 minutes if you are creating this sandbox for the first time...')
69
+ sb = modal.Sandbox.create('sleep', 'infinity',
70
+ app=app, image=img, timeout=timeout,
71
+ unencrypted_ports=[22], gpu=gpu, # <4>
72
+ secrets=[modal.Secret.from_dict(secrets)],
73
+ volumes=volumes)
74
+ log.info('✔ sandbox ready')
75
+ return sb
76
+
77
+ # %% ../nbs/01_sandbox.ipynb #02ca8fce
78
+ def get_tunnel(
79
+ sb: modal.Sandbox # Sandbox with an exposed TCP tunnel
80
+ ) -> tuple[str,int]:
81
+ "Get unencrypted host and port for a Sandbox's TCP tunnel."
82
+ t = sb.tunnels()[22]
83
+ host, port = t.unencrypted_host, t.unencrypted_port
84
+ log.info(f'✔ gotten tunnel: {host}:{port}')
85
+ return host, port
86
+
87
+ # %% ../nbs/01_sandbox.ipynb #db3e20e6
88
+ import os
89
+
90
+ # %% ../nbs/01_sandbox.ipynb #76c2029b
91
+ def get_pubkey() -> str:
92
+ "SSH public key from environment."
93
+ if 'SSH_PUBKEY' not in os.environ:
94
+ raise KeyError("SSH_PUBKEY not set — cannot connect to sandbox via SSH")
95
+ return os.environ['SSH_PUBKEY']
96
+
97
+ # %% ../nbs/01_sandbox.ipynb #22acba37
98
+ def inject_pubkey(
99
+ sb :modal.Sandbox, # Sandbox to inject the key into
100
+ pubkey:str # SSH public key string
101
+ ):
102
+ "Inject an SSH public key into the Sandbox's authorized_keys."
103
+ sb.exec('mkdir', '-p', '/root/.ssh')
104
+ sb.exec('bash', '-c', f'echo {pubkey} > /root/.ssh/authorized_keys')
105
+ log.info('✔ public key injected')
106
+
107
+ # %% ../nbs/01_sandbox.ipynb #7c9fbd91
108
+ from time import sleep
109
+
110
+ # %% ../nbs/01_sandbox.ipynb #a2b3362d
111
+ def start_ssh(
112
+ sb: modal.Sandbox # Sandbox with SSH server installed
113
+ ):
114
+ "Start SSH service in the Sandbox, waiting up to ~6 seconds for it to come online."
115
+ sb.exec('service', 'ssh', 'start')
116
+ for _ in range(20):
117
+ proc = sb.exec('service', 'ssh', 'status')
118
+ if 'fail' in proc.stdout.read(): sleep(0.3)
119
+ elif 'run' in proc.stdout.read():
120
+ log.info('✔ started ssh service')
121
+ return
122
+ log.error('✖ failed to start ssh service')
123
+
124
+ # %% ../nbs/01_sandbox.ipynb #1d3817c4
125
+ from fastcore.all import *
126
+
127
+ # %% ../nbs/01_sandbox.ipynb #310fd93d
128
+ def mk_ssh(
129
+ host: str, # Tunnel host
130
+ port: int, # Tunnel port
131
+ ) -> object:
132
+ "Return an SSH function for the given Modal tunnel."
133
+ return lambda *cmd: run('ssh', '-p', str(port),
134
+ '-o', 'StrictHostKeyChecking=no',
135
+ '-o', 'UserKnownHostsFile=~/.ssh/known_hosts',
136
+ '-o', 'ConnectTimeout=10',
137
+ f'root@{host}', *cmd)
138
+
139
+ # %% ../nbs/01_sandbox.ipynb #65fc2209
140
+ def verify_ssh(
141
+ ssh: object # SSH function returned by mk_ssh
142
+ ):
143
+ "Verify SSH connection to Sandbox and print system info."
144
+ h, u, w = ssh('hostname; uname -srmo; whoami').splitlines()[:3]
145
+ sys_name, ver, arch, os_name = u.split()
146
+ gpu = ssh('nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo "no GPU"').strip()
147
+ print(f'System: {sys_name}')
148
+ print(f'Hostname: {h}')
149
+ print(f'User: {w}')
150
+ print(f'Kernel: {ver}')
151
+ print(f'Architecture: {arch}')
152
+ print(f'OS Type: {os_name}')
153
+ print(f'GPU: {gpu}')
154
+
155
+ # %% ../nbs/01_sandbox.ipynb #7bda2361
156
+ def get_apts() -> list[str]:
157
+ "List installed system package names."
158
+ return run('dpkg-query -W -f=\'${Package}\\n\'').splitlines()
159
+
160
+ # %% ../nbs/01_sandbox.ipynb #f0a23ee7
161
+ def get_pips() -> list[str]:
162
+ "List installed Python packages (name==version)."
163
+ return [l for l in run('pip freeze').splitlines() if not l.startswith(('-e', '@'))]
164
+
165
+ # %% ../nbs/01_sandbox.ipynb #60d610ef
166
+ import socket, os
167
+
168
+ # %% ../nbs/01_sandbox.ipynb #e83fa224
169
+ def in_modal(): return socket.gethostname() == 'modal'
170
+
171
+ # %% ../nbs/01_sandbox.ipynb #9fe893b8
172
+ def in_solveit(): return bool(os.environ.get('IN_SOLVEIT'))
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: solveit-modal
3
+ Version: 0.0.1
4
+ Summary: Give SolveIt Modal GPU access
5
+ Author-email: Salman Naqvi <salmanaqvi+github@icloud.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/ForBo7/solveit-modal
8
+ Project-URL: Documentation, https://ForBo7.github.io/solveit-modal/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: fastcore
16
+ Requires-Dist: ipyfernel
17
+ Requires-Dist: modal
18
+ Dynamic: license-file
19
+
20
+ # solveit-modal
21
+
22
+
23
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
24
+
25
+ This file will become your README and also the index of your
26
+ documentation.
27
+
28
+ ## Developer Guide
29
+
30
+ If you are new to using `nbdev` here are some useful pointers to get you
31
+ started.
32
+
33
+ ### Install solveit_modal in Development mode
34
+
35
+ ``` sh
36
+ # make sure solveit_modal package is installed in development mode
37
+ $ pip install -e .
38
+
39
+ # make changes under nbs/ directory
40
+ # ...
41
+
42
+ # compile to have changes apply to solveit_modal
43
+ $ nbdev_prepare
44
+ ```
45
+
46
+ ## Usage
47
+
48
+ ### Installation
49
+
50
+ Install latest from the GitHub
51
+ [repository](https://github.com/ForBo7/solveit-modal):
52
+
53
+ ``` sh
54
+ $ pip install git+https://github.com/ForBo7/solveit-modal.git
55
+ ```
56
+
57
+ or from [conda](https://anaconda.org/ForBo7/solveit-modal)
58
+
59
+ ``` sh
60
+ $ conda install -c ForBo7 solveit_modal
61
+ ```
62
+
63
+ or from [pypi](https://pypi.org/project/solveit-modal/)
64
+
65
+ ``` sh
66
+ $ pip install solveit_modal
67
+ ```
68
+
69
+ ### Documentation
70
+
71
+ Documentation can be found hosted on this GitHub
72
+ [repository](https://github.com/ForBo7/solveit-modal)’s
73
+ [pages](https://ForBo7.github.io/solveit-modal/). Additionally you can
74
+ find package manager specific guidelines on
75
+ [conda](https://anaconda.org/ForBo7/solveit-modal) and
76
+ [pypi](https://pypi.org/project/solveit-modal/) respectively.
77
+
78
+ ## How to use
79
+
80
+ Fill me in please! Don’t forget code examples:
81
+
82
+ ``` python
83
+ 1+1
84
+ ```
85
+
86
+ 2
@@ -0,0 +1,12 @@
1
+ solveit_modal/__init__.py,sha256=sXLh7g3KC4QCFxcZGBTpG2scR7hmmBsMjq6LqRptkRg,22
2
+ solveit_modal/_modidx.py,sha256=If7WUw6a-uliA1-VmXKWcZNezgjvQYpstqi7Eou4rXM,4764
3
+ solveit_modal/core.py,sha256=BUJ7ffYsJ8CP2SdWZ087Jp2Zqx3tGl5FpjNuZsJq4Wg,3605
4
+ solveit_modal/gpu.py,sha256=07mp2B0eGsl2Jn4GhqY1-P0pzW6FTx_sRSNsiVnPpaw,4247
5
+ solveit_modal/kernel.py,sha256=fSXb0_epMcqEbSl6Pc3_0BjltU7wTM-Lmurl1fe5FGo,2227
6
+ solveit_modal/sandbox.py,sha256=GhCuYb9aLpkMGpF39zkgOrY8OZ7jk0cQyksAgtOlmDI,6495
7
+ solveit_modal-0.0.1.dist-info/licenses/LICENSE,sha256=xV8xoN4VOL0uw9X8RSs2IMuD_Ss_a9yAbtGNeBWZwnw,11337
8
+ solveit_modal-0.0.1.dist-info/METADATA,sha256=tsKBpYakE8rx0AUSh_VMmza6NDBcAZ9aThzPZBlep18,1967
9
+ solveit_modal-0.0.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ solveit_modal-0.0.1.dist-info/entry_points.txt,sha256=76PdtiPQYeRpOGRX8nmvA2rVCmjc5uelbokqUQWupl4,48
11
+ solveit_modal-0.0.1.dist-info/top_level.txt,sha256=fI98PWFupfdvPWkynNnIuwN6m3-3NAqpkIyTTF87gAQ,14
12
+ solveit_modal-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ solveit_modal = solveit_modal._modidx:d
@@ -0,0 +1,201 @@
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 2022, fastai
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.
@@ -0,0 +1 @@
1
+ solveit_modal