File size: 8,933 Bytes
f1adc24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Setup script for minimoX - automates the installation and setup process.
Similar to run_eval.py but for initial setup.
"""

import subprocess
import os
import time
from pathlib import Path

# ---- edit these ----

# Git repository URL (use SSH for private repos, HTTPS for public)
REPO_URL = "https://github.com/ayush1801/minimoX.git"  # or "git@github.com:ayush1801/minimoX.git" for SSH
CLONE_DIR = Path.home() / "minimoX"  # Where to clone the repo
ENV_NAME = "minimo_new"  # Conda environment name
PYTHON_VERSION = "3.11.10"
REDIS_PORT = 6379
NUM_GPUS = 4  # Number of GPU workers to start (0-3)
WORKER_CONCURRENCY = 4
WORKER_PREFETCH_MULTIPLIER = 1

# Paths (will be set based on CLONE_DIR)
LEARNING_DIR = None  # Will be set to CLONE_DIR / "learning"
ENVIRONMENT_DIR = None  # Will be set to CLONE_DIR / "environment"

# --------------------

def run(cmd: list[str], check: bool = True, cwd: Path | None = None, shell: bool = False):
    """Run a command and optionally check for errors."""
    print(f"[RUNNING] {' '.join(cmd) if isinstance(cmd, list) else cmd}")
    if shell:
        result = subprocess.run(cmd, shell=True, check=check, cwd=cwd)
    else:
        result = subprocess.run(cmd, check=check, cwd=cwd)
    return result

def run_shell(cmd: str, check: bool = True, cwd: Path | None = None):
    """Run a shell command."""
    return run(cmd, check=check, cwd=cwd, shell=True)

def has_session(name: str) -> bool:
    """Check if a tmux session exists."""
    return subprocess.run(["tmux", "has-session", "-t", name],
                          stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0

def kill_session(name: str):
    """Kill a tmux session if it exists."""
    if has_session(name):
        print(f"[KILLING] tmux session: {name}")
        run(["tmux", "kill-session", "-t", name])

def create_tmux_session(name: str, command: str):
    """Create a tmux session with a command."""
    if has_session(name):
        print(f"[SKIPPING] tmux session {name} already exists")
        return
    print(f"[CREATING] tmux session: {name}")
    run(["tmux", "new-session", "-d", "-s", name, "bash", "-lc", command])

def check_command_exists(cmd: str) -> bool:
    """Check if a command exists in PATH."""
    return subprocess.run(["which", cmd], 
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0

def main():
    # Set paths
    global LEARNING_DIR, ENVIRONMENT_DIR
    LEARNING_DIR = CLONE_DIR / "learning"
    ENVIRONMENT_DIR = CLONE_DIR / "environment"
    
    print("=" * 60)
    print("minimoX Setup Script")
    print("=" * 60)
    print(f"Repository: {REPO_URL}")
    print(f"Clone directory: {CLONE_DIR}")
    print(f"Conda environment: {ENV_NAME}")
    print(f"Python version: {PYTHON_VERSION}")
    print(f"Number of GPU workers: {NUM_GPUS}")
    print("=" * 60)
    
    # Step 1: Clone repository (if not already cloned)
    if not CLONE_DIR.exists():
        print("\n[STEP 1] Cloning repository...")
        CLONE_DIR.parent.mkdir(parents=True, exist_ok=True)
        run(["git", "clone", REPO_URL, str(CLONE_DIR)])
    else:
        print(f"\n[STEP 1] Repository already exists at {CLONE_DIR}, skipping clone")
        print("         (To re-clone, delete the directory first)")
    
    # Step 2: Create conda environment
    print("\n[STEP 2] Setting up conda environment...")
    if not check_command_exists("conda"):
        raise RuntimeError("conda not found in PATH. Please install conda/miniconda first.")
    
    # Check if environment exists
    env_check = subprocess.run(
        ["conda", "env", "list", "--json"],
        capture_output=True,
        text=True
    )
    env_exists = ENV_NAME in env_check.stdout
    
    if not env_exists:
        print(f"Creating conda environment: {ENV_NAME}")
        run(["conda", "create", "-n", ENV_NAME, f"python={PYTHON_VERSION}", "-y"])
    else:
        print(f"Conda environment {ENV_NAME} already exists, skipping creation")
    
    # Step 3: Install maturin and rust
    print("\n[STEP 3] Installing maturin and rust...")
    # Use conda run to install maturin in the environment
    run(["conda", "run", "-n", ENV_NAME, "pip", "install", "maturin"])
    run(["conda", "install", "-c", "conda-forge", "rust", "-y"])
    
    # Step 4: Build Rust components
    print("\n[STEP 4] Building Rust components...")
    if not (ENVIRONMENT_DIR / "target" / "release" / "peano").exists():
        print("Building with maturin...")
        run(["conda", "run", "-n", ENV_NAME, "maturin", "dev", "--release"], cwd=ENVIRONMENT_DIR)
        
        print("Building peano binary...")
        run(["cargo", "build", "--bin", "peano", "--release"], cwd=ENVIRONMENT_DIR)
        
        # Test peano
        print("Testing peano binary...")
        peano_bin = ENVIRONMENT_DIR / "target" / "release" / "peano"
        if peano_bin.exists():
            result = run_shell(
                f"{peano_bin} theories/natural_number_game.p t_example1",
                cwd=ENVIRONMENT_DIR,
                check=False
            )
            if result.returncode == 0:
                print("[SUCCESS] Peano binary test passed")
            else:
                print("[WARNING] Peano binary test failed, but continuing...")
        else:
            print("[ERROR] Peano binary not found after build")
    else:
        print("Rust components already built, skipping...")
    
    # Step 5: Install Python requirements
    print("\n[STEP 5] Installing Python requirements...")
    requirements_file = LEARNING_DIR / "requirements.txt"
    if requirements_file.exists():
        run(["conda", "run", "-n", ENV_NAME, "pip", "install", "-r", str(requirements_file)])
    else:
        print(f"[WARNING] requirements.txt not found at {requirements_file}")
    
    # # Step 6: Install redis-server (if not already installed)
    # print("\n[STEP 6] Setting up Redis...")
    # if not check_command_exists("redis-server"):
    #     print("Installing redis-server...")
    #     run_shell("sudo apt install -y redis-server", check=False)
    # else:
    #     print("redis-server already installed")
    
    # # Step 7: Start Redis server in tmux
    # print("\n[STEP 7] Starting Redis server in tmux...")
    # redis_session = "minimo_redis"
    # kill_session(redis_session)
    # create_tmux_session(redis_session, f"redis-server --port {REDIS_PORT}")
    # print(f"[INFO] Redis running in tmux session: {redis_session}")
    
    # # Step 8: Start Celery workers in tmux
    # print("\n[STEP 8] Starting Celery workers in tmux...")
    # for gpu_id in range(NUM_GPUS):
    #     session_name = f"minimo_worker_gpu{gpu_id}"
    #     kill_session(session_name)
        
    #     # Create session and send commands
    #     run(["tmux", "new-session", "-d", "-s", session_name, "bash", "-lc", "echo started; exec bash"])
        
    #     # Wait a bit for session to initialize
    #     time.sleep(0.5)
        
    #     # Initialize conda and activate environment
    #     subprocess.run(["tmux", "send-keys", "-t", f"{session_name}:0.0", 
    #                    "source ~/.bashrc 2>/dev/null || true", "C-m"])
    #     subprocess.run(["tmux", "send-keys", "-t", f"{session_name}:0.0", 
    #                    "conda init bash 2>/dev/null || true", "C-m"])
    #     subprocess.run(["tmux", "send-keys", "-t", f"{session_name}:0.0", 
    #                    "bash", "C-m"])
    #     subprocess.run(["tmux", "send-keys", "-t", f"{session_name}:0.0", 
    #                    f"conda activate {ENV_NAME}", "C-m"])
    #     subprocess.run(["tmux", "send-keys", "-t", f"{session_name}:0.0", 
    #                    f"cd {LEARNING_DIR}", "C-m"])
        
    #     # Start celery worker
    #     celery_cmd = (
    #         f"CUDA_VISIBLE_DEVICES={gpu_id} "
    #         f"celery -A worker:app worker "
    #         f"--loglevel=INFO "
    #         f"--concurrency={WORKER_CONCURRENCY} "
    #         f"--prefetch-multiplier={WORKER_PREFETCH_MULTIPLIER} "
    #         f"--hostname gpu{gpu_id}@%h"
    #     )
    #     subprocess.run(["tmux", "send-keys", "-t", f"{session_name}:0.0", 
    #                    celery_cmd, "C-m"])
    #     print(f"[INFO] Celery worker for GPU {gpu_id} running in tmux session: {session_name}")
    
    # # Summary
    # print("\n" + "=" * 60)
    # print("Setup Complete!")
    # print("=" * 60)
    # print(f"\nConda environment: {ENV_NAME}")
    # print(f"Activate with: conda activate {ENV_NAME}")
    # print(f"\nTmux sessions created:")
    # print(f"  - minimo_redis (Redis server)")
    # for gpu_id in range(NUM_GPUS):
    #     print(f"  - minimo_worker_gpu{gpu_id} (Celery worker on GPU {gpu_id})")
    # print(f"\nAttach to sessions with: tmux attach -t <session_name>")
    # print(f"\nWorking directory: {LEARNING_DIR}")
    # print("=" * 60)

if __name__ == "__main__":
    main()