File size: 5,104 Bytes
1c9b5b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c2701e
 
1c9b5b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Persistent zero-paid-resource pipeline. Every stage records its real exit code."""
import json
import os
import subprocess
import time
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
LOGS = ROOT/'logs'
LOGS.mkdir(exist_ok=True)
RUNTIME = ROOT/'.runtime'/'python.exe'
DOWNLOAD = ROOT/'.venv-deploy'/'Scripts'/'python.exe'
STATE = {'pid':os.getpid(),'started_at':datetime.now(timezone.utc).isoformat(),'status':'running','stages':{}}
HANDLES = []


def save():
    STATE['last_updated_at']=datetime.now(timezone.utc).isoformat()
    temporary = LOGS/'pipeline-status.tmp'
    temporary.write_text(json.dumps(STATE,ensure_ascii=False,indent=2),encoding='utf-8')
    temporary.replace(LOGS/'pipeline-status.json')


def launch(name, python, *args):
    output = (LOGS/(name+'.txt')).open('a',encoding='utf-8')
    output.write('\n--- New attempt '+datetime.now(timezone.utc).isoformat()+' ---\n'); output.flush()
    HANDLES.append(output)
    env = dict(os.environ,PYTHONUTF8='1',PYTHONUNBUFFERED='1',NEXTGPT_LOW_VRAM='1')
    env.pop('CUDA_VISIBLE_DEVICES',None)
    process = subprocess.Popen([str(python),'-u','-X','utf8',*args],cwd=ROOT,env=env,
        stdout=output,stderr=subprocess.STDOUT,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0)
    STATE['stages'][name]={'pid':process.pid,'status':'running','started_at':datetime.now(timezone.utc).isoformat()}
    save()
    return process


def wait(name, process):
    while process.poll() is None:
        save()
        time.sleep(5)
    code = process.returncode
    STATE['stages'][name].update(status='completed' if code==0 else 'failed',returncode=code,
                                 finished_at=datetime.now(timezone.utc).isoformat())
    save()
    return code


def main():
    import msvcrt
    with (LOGS/'pipeline.lock').open('a+b') as lock:
        lock.seek(0)
        if lock.read(1)==b'':
            lock.write(b'0'); lock.flush()
        lock.seek(0)
        msvcrt.locking(lock.fileno(),msvcrt.LK_NBLCK,1)
        save()
        jobs = [
            ('download_llama',launch('download_llama',DOWNLOAD,'scripts/download_core_parallel.py','--only','llama','--skip-imagebind')),
            ('download_delta',launch('download_delta',DOWNLOAD,'scripts/download_core_parallel.py','--only','vicuna_delta','--skip-imagebind')),
            ('download_imagebind',launch('download_imagebind',DOWNLOAD,'scripts/download_imagebind_parallel.py')),
        ]
        codes=[]
        pending=dict(jobs)
        attempts={name:1 for name,_ in jobs}
        commands={
            'download_llama':(DOWNLOAD,'scripts/download_core_parallel.py','--only','llama','--skip-imagebind'),
            'download_delta':(DOWNLOAD,'scripts/download_core_parallel.py','--only','vicuna_delta','--skip-imagebind'),
            'download_imagebind':(DOWNLOAD,'scripts/download_imagebind_parallel.py'),
        }
        component=None
        while pending:
            for name,process in list(pending.items()):
                if process.poll() is not None:
                    code=wait(name,process)
                    if code and attempts[name]<4:
                        attempts[name]+=1
                        pending[name]=launch(name,*commands[name])
                        STATE['stages'][name]['attempt']=attempts[name]
                        save()
                        continue
                    codes.append(code)
                    del pending[name]
                    if name=='download_imagebind' and process.returncode==0:
                        component=launch('imagebind_component',RUNTIME,'scripts/check_imagebind_component.py')
            save()
            time.sleep(5)
        if component is not None:
            wait('imagebind_component',component)
        if any(codes):
            STATE['status']='download_failed'; save(); return
        if wait('merge_vicuna',launch('merge_vicuna',RUNTIME,'scripts/merge_vicuna_streaming.py')):
            STATE['status']='merge_failed'; save(); return
        first = wait('first_inference',launch('first_inference',RUNTIME,'scripts/run_local_gpu.py'))
        # Current agreed scope: real image-to-text inference and a report.
        # Four-modality generation stays available as a separate optional CLI.
        wait('validation',launch('validation',RUNTIME,'scripts/record_validation.py'))
        wait('provenance',launch('provenance',RUNTIME,'scripts/update_provenance.py'))
        wait('report',launch('report',RUNTIME,'scripts/finalize_report.py'))
        wait('package',launch('package',DOWNLOAD,'scripts/package_submission.py'))
        publication=wait('publish',launch('publish',DOWNLOAD,'scripts/publish_report.py','CollinMa/nextgpt-chapter6-report'))
        STATE['status']='publication_failed' if publication else 'finished' if first==0 else 'inference_failed'
        save()


if __name__=='__main__':
    try:
        main()
    except Exception as exc:
        STATE.update(status='coordinator_failed',error=type(exc).__name__+': '+str(exc))
        save()
        raise