File size: 11,856 Bytes
d6f1470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15055bb
 
 
 
 
3c4a5ba
6d35eb4
d6f1470
6d35eb4
d6f1470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d35eb4
d6f1470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Agent-loop data generator (Kaggle 2xT4 kernel, one local 4B GGUF model per GPU through llama.cpp).
The MODEL plays the assistant, tests/colab/agentloop_env.py plays the tools and the user.  Every tool call is executed by the simulated world, every rollout is judged against the world state,
only rollouts that really succeed are accepted.  Rejected rollouts are SAVED with their reason (never deleted).  Output repo (append-only commits every few minutes):
    data/<task>/<session>_<seq>.jsonl      accepted rows  {"messages","tools","domain","provider","seed","task_info"}
    rejects/<task>/<session>_<seq>.jsonl   {"reject": reason, "row": {...}}
    status/<kernel>_<session>.json         counters
  python tests/colab/agentloop_run.py --kernel alspark --model_repo XHToken/Spark-X2.6-4B-GGUF --model_file Spark-X2.6-4B-Q8_0.gguf --session_hours 11.2
  python tests/colab/agentloop_run.py --selftest            (no model, no network: an oracle agent plays the assistant; exercises the loop, the buffers and the file layout)"""
import argparse, collections, glob, hashlib, json, os, random, subprocess, sys, threading, time, urllib.request
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE); sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
import agentloop_env as E
from zenyx100m import chat as CH
ap = argparse.ArgumentParser()
ap.add_argument("--kernel", default="alspark"); ap.add_argument("--model_repo", default=""); ap.add_argument("--model_file", default=""); ap.add_argument("--repo", default="Arko007/zenyx-agentic-loops")
ap.add_argument("--session_hours", type=float, default=11.2); ap.add_argument("--np", type=int, default=4); ap.add_argument("--gpus", default="0,1"); ap.add_argument("--upload_sec", type=int, default=300)
ap.add_argument("--first_upload_sec", type=int, default=150); ap.add_argument("--selftest", action="store_true"); ap.add_argument("--selftest_seconds", type=int, default=20)
ap.add_argument("--workdir", default="/kaggle/working/gen4b"); ap.add_argument("--max_per_prompt", type=int, default=4); ap.add_argument("--temp", type=float, default=0.7)
A = ap.parse_args()
W = A.workdir; OUT = f"{W}/agentloop_out"; LLAMA_BIN = f"{W}/llama.cpp/build/bin"; os.makedirs(OUT, exist_ok=True)
T_START = time.time(); DEADLINE = T_START + (A.selftest_seconds if A.selftest else A.session_hours * 3600 - 300); SESSION = f"s{int(T_START)}"
PROVIDER = f"llama.cpp:{os.path.basename(A.model_file)}" if A.model_file else "selftest:oracle"
lock = threading.Lock(); buf_lock = threading.Lock(); stop_all = threading.Event(); stats = collections.Counter(); per_kind = collections.defaultdict(collections.Counter); fails = collections.Counter()
offsets = {}; seq = [0]; seen = set(); per_prompt = collections.Counter()
def log(*a):
    with lock: print(f"[agentloop {time.time() - T_START:7.0f}s]", *a, flush=True)
HF_TOKEN = None
if not A.selftest:
    from zenyx100m.secrets import HF_TOKEN
    from huggingface_hub import HfApi, hf_hub_download, CommitOperationAdd
    api = HfApi(token=HF_TOKEN)
def write_local(kind, d, obj):
    p = f"{OUT}/{kind}/{d}.jsonl"; os.makedirs(os.path.dirname(p), exist_ok=True)
    with buf_lock, open(p, "a", encoding="utf-8") as f: f.write(json.dumps(obj, ensure_ascii=False) + "\n")
def upload_cycle(final=False):
    ops, newoffs = [], {}
    with buf_lock:
        for p in glob.glob(f"{OUT}/*/*.jsonl"):
            kind, d = p.split("/")[-2], os.path.basename(p)[:-6]; off = offsets.get(p, 0)
            with open(p, "rb") as f: f.seek(off); data = f.read()
            cut = data.rfind(b"\n") + 1
            if cut <= 0: continue
            seq[0] += 1; ops.append(("%s/%s/%s_%04d.jsonl" % (kind, d, SESSION, seq[0]), data[:cut])); newoffs[p] = off + cut
        st = {"kernel": A.kernel, "session": SESSION, "provider": PROVIDER, "elapsed_s": round(time.time() - T_START), "stats": dict(stats), "per_task": {k: dict(v) for k, v in per_kind.items()}, "reject_reasons": dict(fails.most_common(25))}
        ops.append((f"status/{A.kernel}_{SESSION}.json", json.dumps(st, indent=1).encode()))
    if len(ops) <= 1 and not final: return
    if A.selftest: log("selftest: would upload", [o[0] for o in ops][:6], "..."); offsets.update(newoffs); return
    for attempt in range(6):
        try: api.create_commit(A.repo, [CommitOperationAdd(path_in_repo=a, path_or_fileobj=b) for a, b in ops], repo_type="dataset", commit_message=f"{A.kernel} {SESSION}: +{len(ops) - 1} files"); break
        except Exception as e: log("upload failed (will retry):", str(e)[:160]); time.sleep(30 * (attempt + 1))
    else: return
    with buf_lock: offsets.update(newoffs)
    log(f"uploaded {len(ops) - 1} files")
def uploader():
    stop_all.wait(A.first_upload_sec); upload_cycle()
    while not stop_all.is_set():
        for _ in range(A.upload_sec):
            if stop_all.wait(1): break
        upload_cycle()
# ------------------------------------------------------------------------------------------------------------- llama.cpp servers
servers = []
def healthy(port):
    try: return b"ok" in urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=5).read()
    except Exception: return False
def start_server(gpu, port):
    env = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu), LD_LIBRARY_PATH=LLAMA_BIN + ":" + os.environ.get("LD_LIBRARY_PATH", ""))
    cmd = [f"{LLAMA_BIN}/llama-server", "-m", MODEL, "-ngl", "99", "-c", str(A.np * 8192), "-np", str(A.np), "--port", str(port), "--jinja"]
    f = open(f"{W}/server_{port}.log", "ab"); return {"gpu": gpu, "port": port, "p": subprocess.Popen(cmd, env=env, stdout=f, stderr=f)}
def wait_ready(s, t=900):
    t0 = time.time()
    while time.time() - t0 < t:
        if s["p"].poll() is not None: return False
        if healthy(s["port"]): return True
        time.sleep(3)
    return False
if not A.selftest:
    MODEL = hf_hub_download(A.model_repo, A.model_file, local_dir=W + "/models", token=None)
    for k, g in enumerate(A.gpus.split(",")): servers.append(start_server(int(g), 8080 + k))
    oks = [wait_ready(sv) for sv in servers]; log("servers ready:", oks)
    if not all(oks): raise SystemExit("servers failed to start")
    def watchdog():
        while not stop_all.wait(60):
            for s in servers:
                if s["p"].poll() is not None or not healthy(s["port"]):
                    log(f"server {s['port']} down - restarting")
                    try: s["p"].kill()
                    except Exception: pass
                    s.update(start_server(s["gpu"], s["port"])); wait_ready(s)
    threading.Thread(target=watchdog, daemon=True).start()
# ------------------------------------------------------------------------------------------------------------- one rollout
POLICY = ("\n\nWorking rules (follow them silently, never mention them): (1) Use a tool only when it is needed; when you call a tool, your whole reply is just the tool call. "
          "(2) If a required detail is missing (which city, which recipient, what time...), ask the user ONE short question and wait for the answer; never guess it. But if the user already gave everything, do not ask. "
          "(3) Before deleting or overwriting anything, ask the user to confirm and wait. "
          "(4) If a tool returns an error, fix the problem when you sensibly can (for example list the folder to find the right file name) or retry once when the error is temporary; if it still fails, say so honestly and do not invent results. "
          "(5) If a tool finds nothing, say that nothing was found; never invent data. (6) If a job is still running, check its status again until it is done, and only then give the result. "
          "(7) If none of your tools can do what is asked, say you can't do that with the tools you have. (8) Answer in 1-3 short, friendly sentences (an occasional emoji is fine, no long markdown), and report tool values exactly as returned.")
def to_openai(system, tools, tr, kind=None):
    """the assistant sees EXACTLY the training prompt: system text + '# Tools' block (chat.system_with_tools); tool results become user turns '<tool_response>..</tool_response>' (merged when consecutive)"""
    msgs = [{"role": "system", "content": (CH.system_with_tools(system, tools) or "") + POLICY + E.gen_hint(kind, tr)}]
    for m in tr:
        if m["role"] == "tool":
            piece = f"<tool_response>{m['content']}</tool_response>"
            if msgs[-1].get("_tool"): msgs[-1]["content"] += "\n" + piece
            else: msgs.append({"role": "user", "content": piece, "_tool": True})
        else: msgs.append({"role": m["role"], "content": m["content"]})
    return [{k: v for k, v in m.items() if k != "_tool"} for m in msgs]
def chat_call(port, messages):
    body = {"messages": messages, "temperature": A.temp, "top_p": 0.95, "max_tokens": 400, "chat_template_kwargs": {"enable_thinking": False}}
    r = json.loads(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=600).read())
    return r["choices"][0]["message"]["content"] or ""
def key_of(task, tr): return hashlib.sha1(json.dumps([task.system, tr], ensure_ascii=False).encode()).hexdigest()
def worker(wid, port):
    n = 0
    while not stop_all.is_set() and time.time() < DEADLINE:
        n += 1; seed = f"{SESSION}-{wid}-{n}"; rng = random.Random(seed); task = E.make_task(rng)
        if A.selftest:
            sys.path.insert(0, os.path.join(os.path.dirname(HERE), ".")); import test_agentloop_env as TA
            gen = TA.oracle(task)
        else:
            gen = lambda system, tools, tr, port=port, kind=task.kind: chat_call(port, to_openai(system, tools, tr, kind))
        try: tr, reason = E.rollout(task, gen)
        except Exception as e:
            with lock: stats["call errors"] += 1
            log("call error:", repr(e)[:140]); time.sleep(5); continue
        row = E.to_row(task, tr, PROVIDER, seed); kind = task.kind
        if reason is None:
            k = key_of(task, tr); pk = (kind, task.user)
            with lock:
                dup = k in seen or per_prompt[pk] >= A.max_per_prompt
                if not dup: seen.add(k); per_prompt[pk] += 1
            if dup: reason = "duplicate or too many rows for the same prompt"
        with lock:
            stats["attempts"] += 1; per_kind[kind]["attempts"] += 1
            if reason: stats["rejected"] += 1; per_kind[kind]["rejected"] += 1; fails[f"{kind}: {reason[:70]}"] += 1
            else: stats["accepted"] += 1; per_kind[kind]["accepted"] += 1
        if reason: write_local("rejects", kind, {"reject": reason, "row": row})
        else: write_local("data", kind, row)
        if stats["attempts"] == 400 and stats["accepted"] < 12 and not A.selftest:
            log("ABORT: acceptance under 3% after 400 rollouts - see rejects/ for the reasons"); stop_all.set()
threads = [threading.Thread(target=worker, args=(k, (servers[k % len(servers)]["port"] if servers else 0))) for k in range(A.np * max(1, len(servers)))]
threading.Thread(target=uploader, daemon=True).start()
for t in threads: t.start()
last = time.time()
while any(t.is_alive() for t in threads):
    time.sleep(5)
    if time.time() - last > 120: last = time.time(); log(f"{dict(stats)} | rejects {dict(fails.most_common(4))}")
log("workers finished - final flush"); stop_all.set(); time.sleep(2); upload_cycle(final=True)
for s in servers:
    try: s["p"].kill()
    except Exception: pass
try:
    import shutil; shutil.make_archive("/kaggle/working/agentloop_rows_backup" if os.path.isdir("/kaggle/working") else OUT + "_backup", "gztar", OUT)
except Exception as e: log("backup archive failed:", str(e)[:100])
log(f"DONE: {dict(stats)} | per task { {k: dict(v) for k, v in per_kind.items()} }")