File size: 7,150 Bytes
6118a66 | 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 | """Standalone Modal app (does not touch the deployed training app): conversation 'chat then come back' test."""
import json
import os
from pathlib import Path
import modal
REMOTE_DIR = "/root/LongTearmMemory"
app = modal.App("ltm-chat-test")
volume = modal.Volume.from_name("long-term-memory-vol")
image = (
modal.Image.debian_slim(python_version="3.11")
.pip_install("torch>=2.4.0", "transformers>=4.45.0", "accelerate", "numpy", "flash-linear-attention", "huggingface_hub")
.add_local_dir(local_path=str(Path(__file__).resolve().parent), remote_path=REMOTE_DIR,
ignore=[".env", ".git", "__pycache__", "checkpoints*", "*.pt", "*.safetensors", "hf_release",
"dataset/generated_backup_v1", "dataset/generated_hard"])
)
@app.function(image=image, gpu=["L4", "A10G"], timeout=4 * 3600, volumes={"/vol": volume}, env={"HF_HOME": "/vol/hf_cache"})
def chat_test(variant: str = "v4_atlas_wide", n: int = 40) -> dict:
import sys
os.chdir(REMOTE_DIR)
sys.path.insert(0, REMOTE_DIR)
from eval_chat_return import run_chat_eval
r = run_chat_eval(variant, f"/vol/checkpoints/unified_nested_L18_{variant}_blank.pt", n)
Path(f"/vol/results/eval_{variant}_chat.json").write_text(json.dumps(r, ensure_ascii=False, indent=2))
volume.commit()
return r
@app.local_entrypoint()
def main(variant: str = "v4_atlas_wide", n: int = 40):
r = chat_test.remote(variant=variant, n=n)
out = Path(__file__).resolve().parent / "results" / f"eval_{variant}_chat.json"
out.write_text(json.dumps(r, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({k: v for k, v in r.items() if k != "transcripts"}, indent=2))
@app.function(image=image, gpu=["L4", "A10G"], timeout=3600, volumes={"/vol": volume}, env={"HF_HOME": "/vol/hf_cache"})
def smoke_v41(variant: str = "v4_atlas_wide") -> str:
import random, sys, time
import torch
os.chdir(REMOTE_DIR)
sys.path.insert(0, REMOTE_DIR)
import train_v4 as T
from config import ProjectConfig
from Model.qwen_memory import QwenMemoryWrapper
from train_nested import variant_options
cfg = ProjectConfig(dtype=torch.bfloat16, **variant_options(variant))
w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
T.load_resized(w, f"/vol/checkpoints/unified_nested_L18_{variant}_blank.pt")
P = T.Pools("train")
bank = T.build_gen_bank(w, P, n_iapp=8, n_msc=4)
print("bank sample", bank[0][0], "->", w.tokenizer.decode(bank[0][1])[:150], flush=True)
rng = random.Random(0)
params = [p for m in w.mems for p in m.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=1e-4)
t0 = time.time()
for i in range(6):
w.model.train()
ep = T.sample_episode(P, [], rng)
ep["general"] = [("__GEN__",) + tuple(rng.choice(bank))]
ep["sequential"] = i % 2 == 0
if i == 3:
ep["qa"] = []
loss, info = T.run_multi(w, ep, "cuda")
opt.zero_grad(); loss.backward(); opt.step(); w.memory._grad_state = None
print(i, round(float(loss), 3), {k: round(v, 3) for k, v in info.items() if isinstance(v, float)}, flush=True)
print("sec/step", (time.time() - t0) / 6, "mem GB", torch.cuda.max_memory_allocated() / 1e9, flush=True)
w.model.eval()
print("chat_check", T.chat_check(w, n=2), flush=True)
return "ok"
@app.function(image=image, gpu=["L4", "A10G"], timeout=3600, volumes={"/vol": volume}, env={"HF_HOME": "/vol/hf_cache"})
def smoke_lora_v5() -> str:
import random, sys
import torch
os.chdir(REMOTE_DIR)
sys.path.insert(0, REMOTE_DIR)
import train_v4 as T
from config import ProjectConfig
from Model.qwen_memory import QwenMemoryWrapper
from train_nested import variant_options
cfg = ProjectConfig(dtype=torch.bfloat16, **variant_options("v5_l10"))
w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
T.load_resized(w, "/vol/checkpoints/unified_nested_L18_v4_atlas_blank.pt")
lm = T.add_lora_all(w, 16, w.hook_layer_idx + 1)
print("lora linears", len(lm), flush=True)
P = T.Pools("train")
bank = T.build_gen_bank(w, P, n_iapp=4, n_msc=2)
params = [p for m in w.mems for p in m.parameters() if p.requires_grad] + [p for m in lm for p in (m.A, m.B)]
opt = torch.optim.AdamW(params, lr=1e-4)
rng = random.Random(1)
for i in range(3):
ep = T.sample_episode(P, [], rng)
ep["general"] = [("__GEN__",) + tuple(rng.choice(bank))]
loss, info = T.run_multi(w, ep, "cuda")
opt.zero_grad(); loss.backward()
g_peer = sum(float(p.grad.abs().sum()) for p in w.mems[1].parameters() if p.grad is not None)
g_lora = sum(float(m.B.grad.abs().sum()) for m in lm if m.B.grad is not None)
opt.step(); w.memory._grad_state = None
print(i, round(float(loss), 3), "grad peer(L10)", round(g_peer, 4), "grad lora", round(g_lora, 4), flush=True)
T.save_model(w, "/tmp/m.pt")
w2 = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
r = w2.model.load_state_dict(torch.load("/tmp/m.pt"), strict=False)
print("reload missing", len(r.missing_keys), "unexpected", len(r.unexpected_keys), r.unexpected_keys[:3], flush=True)
w.model.eval(); w2.model.eval()
ids = w.tokenizer("สวัสดีครับ", return_tensors="pt").input_ids.cuda()
with torch.no_grad():
w.memory.reset_memory(); w2.memory.reset_memory()
d = (w.model(input_ids=ids).logits - w2.model(input_ids=ids).logits).abs().max()
print("merged vs live max logit diff", float(d), flush=True)
return "ok"
@app.function(image=image, gpu=["L4", "A10G"], timeout=3600, volumes={"/vol": volume}, env={"HF_HOME": "/vol/hf_cache"})
def smoke_rl(variant: str = "v4_atlas_wide") -> str:
import random, sys, time
import torch
os.chdir(REMOTE_DIR)
sys.path.insert(0, REMOTE_DIR)
import train_rl as R
import train_v4 as T
from config import ProjectConfig
from Model.qwen_memory import QwenMemoryWrapper
from train_nested import variant_options
cfg = ProjectConfig(dtype=torch.bfloat16, **variant_options(variant))
w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
T.load_resized(w, f"/vol/checkpoints/unified_nested_L18_{variant}_blank.pt")
if w.tokenizer.pad_token is None:
w.tokenizer.pad_token = w.tokenizer.eos_token
params = [p for m in w.mems for p in m.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=5e-5)
P = T.Pools("train")
rng = random.Random(3)
t0 = time.time()
for i in range(8):
loss, info = R.grpo_step(w, P, rng, "cuda", G=8)
if loss is not None:
opt.zero_grad(); loss.backward()
g = sum(float(p.grad.abs().sum()) for p in params if p.grad is not None)
opt.step()
else:
g = 0.0
w.memory._grad_state = None
print(i, info, "loss", None if loss is None else round(float(loss), 4), "grad", round(g, 3), flush=True)
print("sec/step", (time.time() - t0) / 8, "mem GB", torch.cuda.max_memory_allocated() / 1e9, flush=True)
return "ok"
|