Infatoshi's picture
Add files using upload-large-folder tool
22e2264 verified
Raw History Blame Contribute Delete
4.7 kB
"""The overlapped loop's equality check (netherite lane/rlasync): a seeded rollout through mcsr.rl.rollout.Runner
(lane/rlbind's synchronous loop, its uniforms set from (seed, env, step) as mcsr.rl.arollout's) and through
mcsr.rl.arollout.AsyncRunner (overlapped), on the same envs and policy: every act sent to every env, the records the
learner reads (frame embeddings, camera bins, keys, log-probabilities, the loss mask, the rewards) and the episodes'
summaries must be equal, digest for digest.
NETHERITE=... CUDA_VISIBLE_DEVICES=0,1,3 uv run python scripts/nw_async_check.py --n 64 --groups 2 --sims 0 \
--policies 1,2 --seconds 10
"""
import argparse
import hashlib
import json
import os
import sys
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from mcsr import nwrl # noqa: E402 (before torch: one CUDA runtime)
import numpy as np # noqa: E402
import torch # noqa: E402
from mcsr.kvstep import load_policy, EDITS # noqa: E402
from mcsr.rl.arollout import AsyncRunner, seed_sync_runner, trace_sync_runner # noqa: E402
from mcsr.rl.rollout import Runner, summarize # noqa: E402
CKPT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data/play_export/fast-D-s20000.pt")
def h(x):
if isinstance(x, torch.Tensor):
x = x.detach().cpu()
if x.dtype == torch.bfloat16:
x = x.view(torch.int16)
x = x.numpy()
return hashlib.blake2b(np.ascontiguousarray(x).tobytes(), digest_size=8).hexdigest()
def digests(r, rec):
eps = sorted(r.episodes, key=lambda e: e["env"])
return dict(acts=h(np.array(r.acts_hash, np.uint64)), E=h(rec["E"]), CAM=h(rec["CAM"]), KEY=h(rec["KEY"]),
LOGP=h(rec["LOGP"]), MASK=h(rec["MASK"]), REW=h(rec["REW"]),
episodes=hashlib.blake2b(json.dumps(eps, sort_keys=True, default=float).encode(),
digest_size=8).hexdigest())
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--config", default=os.path.join(nwrl.NETHERITE, "configs/speedrun.yaml"))
ap.add_argument("--ckpt", default=CKPT)
ap.add_argument("--n", type=int, default=64)
ap.add_argument("--groups", type=int, default=2)
ap.add_argument("--sims", default="0")
ap.add_argument("--policies", default="1")
ap.add_argument("--seconds", type=float, default=10)
ap.add_argument("--objective", default="logs")
ap.add_argument("--edits", default="version")
ap.add_argument("--seed", type=int, default=1234)
ap.add_argument("--repeat", type=int, default=1, help="overlapped runs after the synchronous one")
a = ap.parse_args()
envs = [nwrl.Env(a.config, a.n, device=int(d)) for d in a.sims.split(",")]
pdevs = [torch.device(f"cuda:{int(d)}") for d in a.policies.split(",")]
torch.cuda.set_device(pdevs[0])
models = [load_policy(a.ckpt, d) for d in pdevs]
edits = EDITS if a.edits == "version" else (a.edits or None)
kw = dict(groups=a.groups, edits=edits, ep_len=int(a.seconds * 20), objective=a.objective, record=True)
sync = trace_sync_runner(seed_sync_runner(Runner(envs, models, pdevs, **kw), a.seed))
t0 = time.time()
rate = sync.run(1, reset=True)
torch.cuda.synchronize(pdevs[0])
ds = digests(sync, dict(E=sync.E, CAM=sync.CAM, KEY=sync.KEY, LOGP=sync.LOGP, MASK=sync.MASK, REW=sync.REW))
print(f"sync: {sync.n} envs x {sync.ep_len} steps in {time.time() - t0:.1f} s ({rate:.0f} env-steps/s) "
f"logs {summarize(sync.episodes)['logs_mean']:.3f} {json.dumps(ds)}", flush=True)
for st in sync.st:
del st.p.k, st.p.v
del sync
torch.cuda.empty_cache()
ok = True
for rep in range(a.repeat):
for overlap in (True,) if rep else (True, False):
ar = AsyncRunner(envs, models, pdevs, seed=a.seed, overlap=overlap, trace=True, **kw)
t0 = time.time()
rate = ar.run(1, reset=True)
da = digests(ar, ar.gather_records(pdevs[0]))
same = da == ds
ok &= same
print(f"{'async' if overlap else 'astep'}: {ar.n} envs x {ar.ep_len} steps in {time.time() - t0:.1f} s "
f"({rate:.0f} env-steps/s) logs {summarize(ar.episodes)['logs_mean']:.3f} {json.dumps(da)} "
f"{'EQUAL' if same else 'DIFFERENT: ' + ' '.join(k for k in ds if ds[k] != da[k])}", flush=True)
for st in ar.st:
del st.p.k, st.p.v
del ar
torch.cuda.empty_cache()
print("ASYNC-CHECK", "PASS" if ok else "FAIL", flush=True)
for env in envs:
env.close()
sys.exit(0 if ok else 1)
if __name__ == "__main__":
main()