emotweetid-ekman7 / laya_opt.py
mahalisyarifuddin's picture
EmoTweetID unified under Ekman's 7 universal emotions: human labels kept, anger pool split into anger/contempt by laya
f5a2109 verified
Raw History Blame Contribute Delete
9.3 kB
"""Memory + throughput optimisations for running `laya` in a 2 vCPU / 2 GB sandbox.
The model, the decision head, the prompt format and the calibration math all stay laya's own
(`laya.load`, `laya.common.build_sequence`, `laya.common.collate_items`,
`laya.common.confidence_from_probs`). What changes is *how much RAM the load costs* and
*how many states share one forward pass*.
1. bf16 encoder. laya forces fp32 on CPU (`agent.py`: `elif self.device.type in
("cpu", "mps"): self.dtype = torch.float32`). The published laya-multilingual checkpoint is
bf16 on disk, so the fp32 path upcasts it to 1.29 GB and the OOM killer ends the run
(exit 137). We build the encoder through HuggingFace's low-cpu-memory path at native bf16
(614 MB) and cast only laya's tiny 2-layer decision head to fp32, which laya's own forward
requires because it pools `.float()` before `act_head`.
2. zero-copy weight load. `safetensors.torch.load_file` materialises the checkpoint a second
time. We hand laya mmap views instead, so the 643 MB are read once, straight from the page
cache, into already-allocated parameters.
3. batched scoring. `Agent.predict` = one forward pass per state, so 475 tweets = 475 passes of
one row each. We pack B states into a single pass and sort them by token length so padding is
near-free.
4. short sequences. laya-multilingual defaults to max_len=1024 / head_max_len=256; attention is
quadratic in length, so the token budget is the biggest speed dial and is set per corpus.
"""
from typing import Dict, List, Sequence
import numpy as np
import torch
from laya.common import QTYPES, build_sequence, collate_items, confidence_from_probs, render_options
BF16 = torch.bfloat16
def _patch_build_model(prepared_dir, dtype):
"""Replace laya.agent.build_model with a low-memory encoder load; laya's head is unchanged.
laya's own builder does `AutoModel.from_config(cfg)`, which allocates the whole encoder at the
default fp32 and then throws those weights away one line later when `Agent.__init__` copies in
the checkpoint. Loading from `prepared_dir` (the same encoder, prefix-stripped) through the
low_cpu_mem_usage dispatcher allocates every tensor once, in bf16, and laysa still overwrites
the head weights from the checkpoint straight afterwards.
"""
import laya.agent as LA
import laya.common as LC
from transformers import AutoModel
def build_model(cfg, encoder_dir=None):
enc = AutoModel.from_pretrained(
prepared_dir or cfg["encoder"],
attn_implementation="sdpa",
dtype=dtype,
low_cpu_mem_usage=True,
)
return LC.DecisionModel(enc, cfg.get("head_layers", 2), len(cfg.get("act_costs", {})) + 1)
LA.build_model = build_model
def _patch_load_file():
"""Make safetensors.torch.load_file hand out mmap views instead of a second full copy.
laya calls `safetensors.torch.load_file` inside `Agent.__init__` and immediately copies the
tensors into the model, so the extra full-materialisation copy is pure waste here.
"""
import safetensors.torch as stt
from zcsafe import load_file_zerocopy, pop_keepalive
def lean_load_file(path, device="cpu"):
w = load_file_zerocopy(path)
pop_keepalive(w) # tensors stay alive via their own memoryview refs
return w
stt.load_file = lean_load_file
def load_agent(ckpt: str = "models/laya-ml/multilingual", encoder_dir: str = "models/enc-bf16",
threads: int = 0, dtype=BF16):
"""`laya.load` on a memory budget. `ckpt` = checkpoint dir holding rl_agent_config.json."""
import os
torch.set_num_threads(threads or max(1, os.cpu_count()))
torch.set_grad_enabled(False)
_patch_build_model(encoder_dir, dtype)
_patch_load_file()
import laya
agent = laya.load(ckpt, device="cpu")
agent.model.act_head.float() # laya pools fp32 into act_head; everything else stays bf16
agent.model.eval()
return agent
class BatchScorer:
"""laya's single-forward-pass-per-state evaluation, but with B states per pass.
Sequence construction, collation, softmax and the entropy confidence are laya's helpers.
"""
def __init__(self, agent, questions: Dict[str, Dict], max_len: int = 384, head_max_len: int = 128):
self.agent = agent
self.qids = list(questions)
self.qlist = [agent._to_internal(questions[q]) for q in self.qids]
self.max_len = max_len
self.head_max_len = head_max_len
def encode(self, state) -> List[dict]:
items = []
for q in self.qlist:
seq, markers = build_sequence(self.agent.tok, state, q, self.max_len, self.head_max_len)
if len(markers) != len(render_options(q)):
raise ValueError("question options exceed head_max_len=%d" % self.head_max_len)
items.append({"ids": seq, "markers": markers, "qtype": QTYPES[q["t"]]})
return items
@torch.no_grad()
def forward(self, encoded: Sequence[List[dict]]) -> List[Dict[str, dict]]:
b = collate_items(list(encoded), self.agent.tok.pad_token_id)
logits, act = self.agent.model(
b["input_ids"], b["attention_mask"], b["marker_pos"], b["marker_mask"], b["qtype"])
logits = logits.float().numpy()
act = torch.softmax(act.float(), -1).numpy()
out, r = [], 0
for ri, items in enumerate(encoded):
res = {}
for qi, qid in enumerate(self.qids):
q = self.qlist[qi]
k = len(items[qi]["markers"])
z = np.asarray(logits[r + qi, :k], dtype=np.float64)
p = np.exp(z - z.max())
p /= p.sum()
# label vocabulary per primitive, in laya's own option order
if q["t"] == "choice":
names = list(q["crit"].keys())
elif q["t"] == "score":
names = [str(i) for i in range(len(q["crit"]))]
else:
names = ["false", "true"]
res[qid] = {
"type": q["t"],
"probabilities": {kk: round(float(v), 6) for kk, v in zip(names, p)},
"argmax_index": int(p.argmax()),
"labels": names,
"choice": names[int(p.argmax())],
"score": round(float((np.arange(k) * p).sum()), 4) if q["t"] == "score" else None,
"noul": float(p[1]) if q["t"] == "noul" else None,
"confidence": round(confidence_from_probs(p, k), 4),
"action": {"act_probability": round(float(act[r + qi, 0]), 4)},
}
out.append(res)
r += len(items)
return out
def token_counts(self, encoded):
return [len(it["ids"]) for it in encoded]
def order_for_packing(tok, texts: List[str], max_len: int):
"""Sort indices by real token length so each batch pads to its own max instead of the global max."""
lens = np.array([min(len(tok(t, add_special_tokens=False)["input_ids"]), max_len) for t in texts])
return np.argsort(lens, kind="stable"), lens
def score_texts(agent, questions, texts, max_len=320, head_max_len=160, token_budget=3072,
progress=None, log=print):
"""Score `texts` with `questions`, packing as many (state x question) rows per forward pass as
`token_budget` allows. States are visited in token-length order, so each batch pads to its own
length instead of to the longest tweet in the corpus.
Returns (results_in_input_order, stats).
"""
import time
scorer = BatchScorer(agent, questions, max_len=max_len, head_max_len=head_max_len)
order, _ = order_for_packing(agent.tok, list(texts), max_len)
encoded = [scorer.encode(texts[i]) for i in order]
# laya pads every row of a pass to that pass's longest sequence, and attention is quadratic in
# it, so grow each batch while (rows x longest sequence x questions) stays inside the budget.
row_len = [max(len(it["ids"]) for it in enc) for enc in encoded]
n_q = len(questions)
results = [None] * len(texts)
t0 = time.time()
n_passes = n_rows = 0
i = 0
while i < len(encoded):
j = i + 1
while j < len(encoded) and (j - i + 1) * n_q * row_len[j] <= token_budget:
j += 1
res = scorer.forward(encoded[i:j])
n_rows += (j - i) * n_q
n_passes += 1
for off, r in enumerate(res):
results[int(order[i + off])] = r
i = j
if progress:
progress(i, len(encoded))
dt = time.time() - t0
stats = {"seconds": round(dt, 1), "docs": len(texts), "forward_passes": n_passes,
"docs_per_pass": round(len(texts) / max(1, n_passes), 2),
"rows": n_rows, "ms_per_doc": round(dt / max(1, len(texts)) * 1000, 1),
"ms_per_row": round(dt / max(1, n_rows) * 1000, 2),
"max_seq_len": max(row_len) if row_len else 0}
log("[laya] %d docs, %d rows in %d forward passes -> %.1fs (%.0f ms/doc, %.1f ms/row)" % (
stats["docs"], n_rows, n_passes, dt, stats["ms_per_doc"], stats["ms_per_row"]))
return results, stats