Auto Upload Agent
v0: 4B 專案骨架 (installpi.sh/memwatch.py/patches/STATUS/AGENTS/sync.sh)
b394bdd
Raw History Blame Contribute Delete
16.4 kB
#!/usr/bin/env python3
"""
memwatch.py — 3GB 總 RAM 硬約束執行器 + SSD page cache 回收者
用法 A (觀測既有行程):
memwatch.py --pid <PID> --limit-gb 3 --interval 1 --json-out stats.json
用法 B (以 3GB 硬上限啟動子行程):
memwatch.py --limit-gb 3 --sweep <GGUF> -- <command...>
================================ 硬約束的定義 ================================
目標: **行程總 RSS (含 page cache) <= 3GB**。
這一點很重要, 之前版本只看「匿名記憶體」是錯的: GGUF 以
``mmap(PROT_READ, MAP_SHARED)`` 對映 (src/llama-mmap.cpp:485-495), 權重頁會
變成行程的 page cache 而算進 RSS —— 舊證據 peak_rss 15.2 GiB 就是這樣來的。
page cache 確實佔用系統 RAM, 所以它必須被算進來, 也必須被真的丟掉。
怎麼讓 RSS 掉下來
------------------
權重是唯讀的乾淨頁, 所以呼叫
posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED)
會直接把它們從 page cache 丟掉 (不需 root, 不需 CAP_SYS_ADMIN, 因為頁是乾淨的)。
本檔的 **reclaimer** 就是一個背景執行緒, 定期對 GGUF 檔案丟 DONTNEED,
讓「幾乎所有動作都在 SSD」不只是設定, 而是可觀測的 RSS 數字。
這也代表 dense 權重是純 streaming: 每個 token 都要從 SSD 重讀整個 15.33 GiB。
這是 dense 模型在 3GB 下的固有代價, 不是可以調掉的開銷。
強制手段 (由嚴到鬆, 自動降級, 全部寫進輸出)
-------------------------------------------
1. cgroup v2 memory.max —— 若容器有委派的 memory controller。這是核心層級的
「總 RSS 含 page cache」上限, 壓力下核心自己會回收權重頁。最強。
2. reclaimer + RLIMIT_DATA —— 不需任何權限:
- reclaimer 讓總 RSS 真的維持在 3GB 以下 (靠 DONTNEED 丟乾淨頁),
- RLIMIT_DATA 給匿名記憶體一個核心層級硬上限 (超標 -> malloc 回 NULL ->
明確崩潰, 而不是被 OOM killer 隨意殺掉)。
3. 純監控 —— 前兩者都拿不到時的退路, 輸出會誠實標示 unenforced。
輸出永遠包含: peak_rss / peak_anon / peak_file / peak_swap, 實際生效的強制手段,
reclaimer 丟掉多少 MiB, 以及從 /proc/<pid>/limits 回讀的 RLIMIT_DATA
(證明限制真的落在行程上, 而不是我們「以為」設了)。
"""
import argparse, json, os, resource, subprocess, sys, threading, time
def read_status(pid):
"""回傳 (rss, anon, file) 分頁統計 (bytes)。"""
try:
with open(f"/proc/{pid}/smaps_rollup") as f:
d = {}
for line in f:
k, _, v = line.partition(":")
v = v.strip()
if v.endswith("kB"):
d[k.strip()] = int(v[:-2].strip()) * 1024
rss = d.get("Rss", 0)
anon = d.get("Anonymous", 0)
fil = d.get("FilePmdMapped", 0) or (rss - anon)
return rss, anon, max(0, fil)
except Exception:
return 0, 0, 0
def read_rlimit_data(pid):
"""從 /proc/<pid>/limits 回讀生效中的 RLIMIT_DATA (bytes)。"""
try:
with open(f"/proc/{pid}/limits") as f:
for line in f:
if line.lower().startswith("max data size"):
# /proc/<pid>/limits reports bytes (the trailing "bytes" unit),
# NOT kilobytes - do not scale. Parsing this wrong reported
# 3221225472*1024 and made the verification a no-op.
soft = line.split()[3]
if soft == "unlimited":
return None
return int(soft)
except Exception:
pass
return None
def cgroup2_usable(base="/sys/fs/cgroup"):
"""memory controller 已委派 且 根目錄可寫 (可建立子 cgroup) 才算可用。"""
try:
with open(os.path.join(base, "cgroup.controllers")) as f:
if "memory" not in f.read().split():
return False, "memory controller 未委派給本容器"
except Exception:
return False, "讀不到 cgroup.controllers"
if not os.access(base, os.W_OK):
return False, f"{base} 唯讀 (無法建立 delegated 子 cgroup)"
return True, ""
def try_cgroup(name, limit_bytes, base="/sys/fs/cgroup"):
try:
with open(os.path.join(base, "cgroup.subtree_control"), "w") as f:
f.write("+memory")
except Exception as e:
return None, f"寫 subtree_control 失敗: {e}"
path = os.path.join(base, name)
try:
os.makedirs(path, exist_ok=True)
with open(os.path.join(path, "memory.swap.max"), "w") as f:
f.write("max")
with open(os.path.join(path, "memory.max"), "w") as f:
f.write(str(limit_bytes))
return path, ""
except Exception as e:
return None, f"建立失敗: {e}"
def attach_cgroup(cg_path, pid):
with open(os.path.join(cg_path, "cgroup.procs"), "w") as f:
f.write(str(pid))
def ensure_swap(swapfile, size_gb):
"""建立並啟用 SSD swapfile (需 CAP_SYS_ADMIN)。"""
try:
if not os.path.exists(swapfile):
subprocess.run(["fallocate", "-l", f"{size_gb}G", swapfile], check=True)
os.chmod(swapfile, 0o600)
subprocess.run(["mkswap", swapfile], check=True, stdout=subprocess.DEVNULL)
if subprocess.run(["swapon", swapfile], capture_output=True).returncode != 0:
return False, "swapon 失敗"
try:
open("/proc/sys/vm/swappiness", "w").write("10")
except Exception:
pass
return True, ""
except Exception as e:
return False, str(e)
class Reclaimer(threading.Thread):
"""背景執行緒: 定期對權重檔丟 POSIX_FADV_DONTNEED, 把乾淨頁真的丟出 page cache。
這是「幾乎所有動作都在 SSD」在量測上唯一說得清楚的證明: 丟完之後總 RSS
會掉下來, 而模型還能繼續正確推理 (下一個 token 再從 SSD 讀回來)。
"""
daemon = True
def __init__(self, paths, interval=0.25):
super().__init__()
self.paths = [p for p in paths if p and os.path.isfile(p)]
self.interval = interval
self.stop_ev = threading.Event()
self.sweeps = 0
self.dropped_mib_estimate = 0.0
self._last_rss = 0
def note_rss(self, rss):
self._last_rss = rss
def run(self):
while not self.stop_ev.is_set():
for p in self.paths:
try:
fd = os.open(p, os.O_RDONLY)
try:
os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)
finally:
os.close(fd)
self.sweeps += 1
except Exception:
pass
self.stop_ev.wait(self.interval)
def stats(self):
return {
"targets": self.paths,
"sweeps": self.sweeps,
"interval_s": self.interval,
"note": "每次 sweep 對權重檔丟 POSIX_FADV_DONTNEED (乾淨頁 -> 直接丟出 page cache, 不需 root)",
}
def write_json(path, obj):
try:
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(obj, f, indent=1)
os.replace(tmp, path)
except Exception:
pass
def snapshot(a, limit, pid, cg_path, methods, enf, peak, peak_swap, over, t0, samples, rec):
return {
"pid": pid,
"limit_bytes": limit,
"metric": "total_rss",
"metric_note": (
"硬約束看的是「總 RSS 含 page cache」。GGUF 以 mmap(PROT_READ, MAP_SHARED) "
"對映, 權重頁會算進 RSS 且真的佔用系統 RAM, 所以必須算進來; "
"reclaimer 靠 POSIX_FADV_DONTNEED 把它們丟回去。"
),
"methods": methods,
"cgroup_enforced": bool(cg_path),
"hard_enforced": bool(cg_path) or enf["reclaimer"]["enabled"] or enf["rlimit_data"]["enabled"],
"enforcement": enf,
"reclaimer": rec.stats() if rec else None,
"peak_rss_bytes": peak["rss"],
"peak_anon_bytes": peak["anon"],
"peak_file_bytes": peak["file"],
"peak_swap_bytes": peak_swap,
"peak_rss_gb": round(peak["rss"] / 2 ** 30, 3),
"peak_anon_gb": round(peak["anon"] / 2 ** 30, 3),
"peak_file_gb": round(peak["file"] / 2 ** 30, 3),
"peak_swap_gb": round(peak_swap / 2 ** 30, 3),
"within_limit": peak["rss"] <= limit,
"over_limit_samples": over,
"duration_s": round(time.time() - t0, 1),
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
"samples": samples,
}
def make_rlimit_preexec(limit_bytes):
"""exec 前設 RLIMIT_DATA = limit (soft 與 hard 一起降, 否則子行程可自行調高)。"""
_, cur_hard = resource.getrlimit(resource.RLIMIT_DATA)
hard = limit_bytes if cur_hard == resource.RLIM_INFINITY else min(limit_bytes, cur_hard)
soft = min(limit_bytes, hard)
def _apply():
resource.setrlimit(resource.RLIMIT_DATA, (soft, hard))
_apply.limit = soft
return _apply
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--pid", type=int)
ap.add_argument("--limit-gb", type=float, default=3.0)
ap.add_argument("--interval", type=float, default=1.0)
ap.add_argument("--json-out", default="")
ap.add_argument("--cgroup-name", default="llama-3g")
ap.add_argument("--swapfile", default="")
ap.add_argument("--swap-gb", type=int, default=0)
ap.add_argument("--sweep", action="append", default=[],
help="要定期丟 DONTNEED 的檔案 (通常是 GGUF); 可重複")
ap.add_argument("--sweep-interval", type=float, default=0.25)
ap.add_argument("--no-sweep", action="store_true", help="停用 reclaimer (對照組)")
ap.add_argument("--rlimit-data", default="auto", help="'auto' | 'off' | bytes")
ap.add_argument("--log", default="")
ap.add_argument("cmd", nargs=argparse.REMAINDER)
a = ap.parse_args()
limit = int(a.limit_gb * 1024 ** 3)
methods, cg_path, child, preexec, rec = [], None, None, None, None
enf = {
"cgroup_v2": {"enabled": False, "reason": ""},
"reclaimer": {"enabled": False, "reason": ""},
"rlimit_data": {"enabled": False, "bytes": None, "readback_bytes": None,
"verified": None, "reason": ""},
"swapfile": {"enabled": False, "reason": ""},
"monitor_only": False,
}
if a.cmd and a.cmd[0] == "--":
a.cmd = a.cmd[1:]
if a.cmd:
ok, why = cgroup2_usable()
if ok:
cg_path, err = try_cgroup(a.cgroup_name, limit)
if cg_path:
enf["cgroup_v2"] = {"enabled": True, "path": cg_path}
methods.append(f"cgroup-v2:memory.max={a.limit_gb}G ({cg_path})")
else:
enf["cgroup_v2"]["reason"] = err
methods.append("cgroup-v2:unavailable")
else:
enf["cgroup_v2"]["reason"] = why
if a.sweep and not a.no_sweep:
rec = Reclaimer(a.sweep, a.sweep_interval)
enf["reclaimer"] = {"enabled": True, "targets": rec.paths}
methods.append(f"reclaimer:POSIX_FADV_DONTNEED x{len(rec.paths)} 檔 (每 {a.sweep_interval}s)")
elif a.no_sweep:
enf["reclaimer"]["reason"] = "使用者停用 (對照組)"
else:
enf["reclaimer"]["reason"] = "未提供 --sweep"
rl = None
if a.rlimit_data == "auto":
rl = limit
elif a.rlimit_data != "off":
try:
rl = int(a.rlimit_data)
except ValueError:
rl = limit
if rl is not None:
preexec = make_rlimit_preexec(rl)
enf["rlimit_data"] = {"enabled": True, "bytes": rl}
methods.append(f"RLIMIT_DATA={rl >> 20}MiB (核心層級, 限制匿名記憶體)")
else:
enf["rlimit_data"]["reason"] = "使用者關閉"
if a.swap_gb:
ok, why = ensure_swap(a.swapfile, a.swap_gb)
enf["swapfile"] = {"enabled": ok, "path": a.swapfile, "gb": a.swap_gb,
"reason": why}
methods.append("swapfile:" + ("ok" if ok else "unavailable"))
if ok:
print("[memcap] swapfile 已啟用: 這是把溢出搬到 SSD, 不是把 RAM 變大",
file=sys.stderr)
if not any(enf[k]["enabled"] for k in ("cgroup_v2", "reclaimer", "rlimit_data")):
enf["monitor_only"] = True
methods.append("monitor-only (僅記錄, 無強制) — 這不是硬約束")
child = subprocess.Popen(a.cmd, env=dict(os.environ), preexec_fn=preexec)
methods.append(f"supervising pid={child.pid}")
pid = child.pid
if cg_path:
try:
attach_cgroup(cg_path, pid)
except Exception as e:
print(f"[memcap] 無法加入 cgroup: {e}", file=sys.stderr)
if preexec is not None:
# readback proves the limit actually reached the child; the kernel
# rounds RLIMIT_DATA up to a whole number of bytes, so compare with a
# small tolerance rather than demanding exact equality
enf["rlimit_data"]["readback_bytes"] = read_rlimit_data(pid)
rb = enf["rlimit_data"]["readback_bytes"]
if rb is None:
enf["rlimit_data"]["verified"] = False
methods.append("WARNING: 無法回讀 RLIMIT_DATA")
elif abs(rb - preexec.limit) > 4096:
enf["rlimit_data"]["verified"] = False
methods.append(f"WARNING: RLIMIT_DATA 回讀 {rb} 與設定值 {preexec.limit} 不符")
else:
enf["rlimit_data"]["verified"] = True
if rec:
rec.start()
else:
pid = a.pid
methods.append("monitor-only (attach)")
rb = read_rlimit_data(pid)
if rb is not None:
enf["rlimit_data"] = {"enabled": True, "bytes": rb, "readback_bytes": rb}
else:
enf["monitor_only"] = True
peak = {"rss": 0, "anon": 0, "file": 0}
peak_swap, samples, over = 0, [], 0
t0 = time.time()
try:
while True:
rss, anon, fil = read_status(pid)
if rss == 0:
break
if rss > peak["rss"]:
peak = {"rss": rss, "anon": anon, "file": fil}
if rec:
rec.note_rss(rss)
try:
sw = int(open(f"/proc/{pid}/status").read().split("VmSwap:")[1].split()[0]) * 1024
peak_swap = max(peak_swap, sw)
except Exception:
pass
if rss > limit:
over += 1
samples.append({"t": round(time.time() - t0, 2), "rss_mb": rss >> 20,
"anon_mb": anon >> 20, "file_mb": fil >> 20})
print(f"[memcap] rss={rss/2**30:.3f}G anon={anon/2**30:.3f}G "
f"file={fil/2**30:.3f}G swap={peak_swap/2**30:.3f}G "
f"limit={a.limit_gb}G" + (" << OVER" if rss > limit else ""), flush=True)
if a.json_out:
write_json(a.json_out, snapshot(a, limit, pid, cg_path, methods, enf,
peak, peak_swap, over, t0, samples, rec))
if child is not None and child.poll() is not None:
break
time.sleep(a.interval)
except KeyboardInterrupt:
pass
if rec:
rec.stop_ev.set()
result = snapshot(a, limit, pid, cg_path, methods, enf, peak, peak_swap, over, t0, samples, rec)
print("[memcap] 結果: " + json.dumps({k: v for k, v in result.items() if k != "samples"},
indent=1))
write_json(a.json_out, result)
if a.log:
try:
with open(a.log, "a") as f:
f.write(json.dumps(result, indent=1) + "\n")
except Exception:
pass
if child is not None:
child.terminate()
try:
child.wait(timeout=10)
except Exception:
child.kill()
return 0 if result["within_limit"] else 2
if __name__ == "__main__":
sys.exit(main())