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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared paths, schema helpers and the vLLM option-letter log-prob client for the
|
| 2 |
+
full-item-pool screening run (exp/analysis/pool/TASK.md).
|
| 3 |
+
|
| 4 |
+
Layout
|
| 5 |
+
exp/results/pool/ small tabular outputs (csv/md) + parquet/duckdb
|
| 6 |
+
pool_items_base.parquet pool_schema.py (all items, TASK schema)
|
| 7 |
+
step0_kept.parquet step0_screen.py (dedup verdict per item)
|
| 8 |
+
screen_counts_full.csv step0_screen.py
|
| 9 |
+
step1/<bench>[.p<j>].jsonl step1_blind.py (one row per item, append-only)
|
| 10 |
+
step2/<bench>[.p<j>].jsonl step2_single_frame.py
|
| 11 |
+
step3/<bench>[.p<j>].jsonl step3_v32_2b.py
|
| 12 |
+
pool_items.parquet, pool.duckdb, pool_summary.md, run_accounting.csv (assemble/accounting)
|
| 13 |
+
bench_exp/work/pool_items_cache/ per-bench enumeration cache (jsonl) for the 88
|
| 14 |
+
benchmarks without a T3 full-text export
|
| 15 |
+
bench_exp/work/pool_embeddings/ bge-large-en-v1.5 cache per bench (ids.json + .npy),
|
| 16 |
+
same layout as exp/data/embeddings/text
|
| 17 |
+
bench_exp/work/pool_frames/<video_id>/ frame_<k>.jpg (448 px long side) + frames.json
|
| 18 |
+
|
| 19 |
+
Item id = the pipeline qid (f"{bench}_{pool_index}", or the stage_b adapter qid for
|
| 20 |
+
MVBench / LVBench / VideoMMMU). video_id = normalized content_hash, or
|
| 21 |
+
"k:" + sha1(video_key)[:16] while the video is not yet normalized.
|
| 22 |
+
"""
|
| 23 |
+
import fcntl
|
| 24 |
+
import hashlib
|
| 25 |
+
import json
|
| 26 |
+
import math
|
| 27 |
+
import os
|
| 28 |
+
import random
|
| 29 |
+
import re
|
| 30 |
+
import sys
|
| 31 |
+
import time
|
| 32 |
+
|
| 33 |
+
HERE = os.path.dirname(os.path.abspath(__file__)) # exp/analysis/pool
|
| 34 |
+
EXP = os.path.abspath(os.path.join(HERE, "..", "..")) # exp
|
| 35 |
+
REPO = os.path.dirname(EXP)
|
| 36 |
+
PIPE = os.path.join(EXP, "pipeline")
|
| 37 |
+
for p in (PIPE, os.path.join(EXP, "t3")):
|
| 38 |
+
if p not in sys.path:
|
| 39 |
+
sys.path.insert(0, p)
|
| 40 |
+
os.environ.setdefault("FINEBENCH_ROUTE", "yt") # FineBench samples were drawn with the YouTube route
|
| 41 |
+
|
| 42 |
+
# Off-cluster runs (exp/analysis/pool/REMOTE_README.md, HF dataset GMLRVigil/BenchCheck-Pool): POOL_BASE
|
| 43 |
+
# replaces the cluster data root (the store / manifest / caches under it are optional for steps 1-3),
|
| 44 |
+
# POOL_FRAMES_DIR points at the unpacked frame cache, POOL_RESULTS_ROOT at the items + step outputs.
|
| 45 |
+
BASE = os.environ.get("POOL_BASE") or "/vast/projects/jgu32/lab/enxin/bench_exp"
|
| 46 |
+
STORE = f"{BASE}/store"
|
| 47 |
+
WORK = f"{BASE}/work"
|
| 48 |
+
NORMALIZED = f"{STORE}/normalized"
|
| 49 |
+
MANIFEST_JSONL = f"{BASE}/logs/manifest.jsonl"
|
| 50 |
+
T3_FULL = f"{BASE}/t3_export_n1_fulltext/full"
|
| 51 |
+
ITEMS_CACHE = f"{WORK}/pool_items_cache"
|
| 52 |
+
EMB_DIR = f"{WORK}/pool_embeddings"
|
| 53 |
+
FRAMES_DIR = os.environ.get("POOL_FRAMES_DIR") or f"{WORK}/pool_frames"
|
| 54 |
+
LOG_DIR = f"{BASE}/logs"
|
| 55 |
+
|
| 56 |
+
RESULTS = os.environ.get("POOL_RESULTS_ROOT") or os.path.join(EXP, "results", "pool") # override for smoke tests
|
| 57 |
+
BASE_PARQUET = os.path.join(RESULTS, "pool_items_base.parquet")
|
| 58 |
+
SCHEMA_MANIFEST = os.path.join(RESULTS, "pool_schema_manifest.csv")
|
| 59 |
+
STEP0_KEPT = os.path.join(RESULTS, "step0_kept.parquet")
|
| 60 |
+
STEP0_REMOVED = os.path.join(RESULTS, "step0_removed.jsonl")
|
| 61 |
+
SCREEN_CSV = os.path.join(RESULTS, "screen_counts_full.csv")
|
| 62 |
+
POOL_PARQUET = os.path.join(RESULTS, "pool_items.parquet")
|
| 63 |
+
POOL_DUCKDB = os.path.join(RESULTS, "pool.duckdb")
|
| 64 |
+
POOL_SUMMARY_MD = os.path.join(RESULTS, "pool_summary.md")
|
| 65 |
+
POOL_SUMMARY_CSV = os.path.join(RESULTS, "pool_summary.csv")
|
| 66 |
+
ACCOUNTING_CSV = os.path.join(RESULTS, "run_accounting.csv")
|
| 67 |
+
|
| 68 |
+
VB_CSV = os.path.join(EXP, "video_benchmarks.csv")
|
| 69 |
+
REGISTRY_CSV = os.path.join(REPO, "meta", "benchmark_registry.csv")
|
| 70 |
+
SAMPLE_DIRS = [os.path.join(EXP, "data", "samples"), os.path.join(EXP, "data", "samples_n1")]
|
| 71 |
+
|
| 72 |
+
HF_HUB = "/vast/projects/jgu32/lab/enxin/cache/hf/hub"
|
| 73 |
+
MODELS = {
|
| 74 |
+
# step -> (served model name, snapshot dir)
|
| 75 |
+
"8b": ("Qwen/Qwen3-VL-8B-Instruct",
|
| 76 |
+
f"{HF_HUB}/models--Qwen--Qwen3-VL-8B-Instruct/snapshots/0c351dd01ed87e9c1b53cbc748cba10e6187ff3b"),
|
| 77 |
+
"2b": ("Qwen/Qwen3-VL-2B-Instruct",
|
| 78 |
+
f"{HF_HUB}/models--Qwen--Qwen3-VL-2B-Instruct/snapshots/89644892e4d85e24eaac8bacfd4f463576704203"),
|
| 79 |
+
}
|
| 80 |
+
BGE_SNAPSHOT = f"{HF_HUB}/models--BAAI--bge-large-en-v1.5/snapshots/d4aa6901d3a41ba39fb536a557fa166f842b0e09"
|
| 81 |
+
|
| 82 |
+
STEPS = {1: "blind", 2: "single_frame", 3: "v32_2b"}
|
| 83 |
+
STEP_MODEL = {1: "8b", 2: "8b", 3: "2b"}
|
| 84 |
+
STEP_DIR = {k: os.path.join(RESULTS, f"step{k}") for k in STEPS}
|
| 85 |
+
|
| 86 |
+
SEED = 42
|
| 87 |
+
N_PERM = 4
|
| 88 |
+
LOG2 = math.log(2.0)
|
| 89 |
+
LP_FLOOR = math.log(1e-6) # letter absent from the top-20 log-probs
|
| 90 |
+
TOP_LOGPROBS = 20
|
| 91 |
+
MAX_OPTIONS = 26 # letters A..Z; more options -> format=open
|
| 92 |
+
LETTERS = [chr(65 + i) for i in range(MAX_OPTIONS)]
|
| 93 |
+
FRAME_LONG_SIDE = 448
|
| 94 |
+
N_FRAMES_V32 = 32
|
| 95 |
+
MID_POS = 16 # stage_p1_runner v_1: grid32[16]
|
| 96 |
+
JPEG_QUALITY = 85
|
| 97 |
+
MAX_ERRORS_PER_ITEM = 3 # error rows before an item is treated as permanently failed
|
| 98 |
+
|
| 99 |
+
# one prompt skeleton for all three steps (intro strings reused from stage_p1_runner)
|
| 100 |
+
PROMPT = "{intro}\n\nQuestion: {q}\nOptions:\n{opts}\nAnswer with the option letter only."
|
| 101 |
+
ASSISTANT_PREFIX = "Answer:" # continue_final_message -> the next token is the letter
|
| 102 |
+
_TOKEN_LETTER = re.compile(r"^\s*[\(\[]?([A-Z])[\)\]\.:]?\s*$")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def log(msg, tag="pool"):
|
| 106 |
+
print(f"[{tag}] {time.strftime('%H:%M:%S')} {msg}", file=sys.stderr, flush=True)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def ensure_dirs():
|
| 110 |
+
for d in (RESULTS, ITEMS_CACHE, EMB_DIR, FRAMES_DIR, LOG_DIR, *STEP_DIR.values()):
|
| 111 |
+
os.makedirs(d, exist_ok=True)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ------------------------------------------------------------------ benches
|
| 115 |
+
def bench_list():
|
| 116 |
+
"""Stems of exp/data/samples/*.jsonl + exp/data/samples_n1/*.jsonl (139 onboarded)."""
|
| 117 |
+
import glob
|
| 118 |
+
names = set()
|
| 119 |
+
for d in SAMPLE_DIRS:
|
| 120 |
+
for p in glob.glob(os.path.join(d, "*.jsonl")):
|
| 121 |
+
if os.path.exists(p):
|
| 122 |
+
names.add(os.path.basename(p)[:-6])
|
| 123 |
+
return sorted(names)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def sample_path(bench):
|
| 127 |
+
for d in SAMPLE_DIRS:
|
| 128 |
+
p = os.path.join(d, f"{bench}.jsonl")
|
| 129 |
+
if os.path.exists(p):
|
| 130 |
+
return p
|
| 131 |
+
return None
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def read_jsonl(path):
|
| 135 |
+
out = []
|
| 136 |
+
with open(path, encoding="utf-8") as f:
|
| 137 |
+
for line in f:
|
| 138 |
+
if line.strip():
|
| 139 |
+
try:
|
| 140 |
+
out.append(json.loads(line))
|
| 141 |
+
except json.JSONDecodeError:
|
| 142 |
+
continue # torn final line of a killed writer
|
| 143 |
+
return out
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def key_of(ref):
|
| 147 |
+
return f"{ref['repo']}::{ref.get('zip_path', '')}::{ref['member']}"
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def manifest_hashes():
|
| 151 |
+
"""video_key -> content_hash for logs/manifest.jsonl status=done rows (last wins)."""
|
| 152 |
+
m = {}
|
| 153 |
+
if not os.path.exists(MANIFEST_JSONL):
|
| 154 |
+
return m
|
| 155 |
+
with open(MANIFEST_JSONL, encoding="utf-8") as f:
|
| 156 |
+
for line in f:
|
| 157 |
+
try:
|
| 158 |
+
r = json.loads(line)
|
| 159 |
+
except Exception:
|
| 160 |
+
continue
|
| 161 |
+
if r.get("status") == "done" and r.get("content_hash") and "::" in str(r.get("key", "")):
|
| 162 |
+
m[r["key"]] = r["content_hash"]
|
| 163 |
+
return m
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def key_video_id(key):
|
| 167 |
+
return "k:" + hashlib.sha1(key.encode("utf-8")).hexdigest()[:16]
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def normalized_path(h):
|
| 171 |
+
return f"{NORMALIZED}/{h}/video.mp4"
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def meta_of(h):
|
| 175 |
+
try:
|
| 176 |
+
return json.load(open(f"{NORMALIZED}/{h}/meta.json"))
|
| 177 |
+
except Exception:
|
| 178 |
+
return None
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
# ------------------------------------------------------------------ options
|
| 182 |
+
_SEQ_PREFIX = re.compile(r"^\s*[\(\[]?([A-Za-z])[\)\]\.:]\s*(.*)$", re.S)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def strip_sequential_prefix(opts):
|
| 186 |
+
"""['A. x', 'B. y'] -> (['x', 'y'], True) when every option carries the letter of
|
| 187 |
+
its position (A, B, C, ...); otherwise the list is returned unchanged."""
|
| 188 |
+
texts = []
|
| 189 |
+
for i, o in enumerate(opts):
|
| 190 |
+
m = _SEQ_PREFIX.match(str(o))
|
| 191 |
+
if not m or m.group(1).upper() != chr(65 + i):
|
| 192 |
+
return [str(o) for o in opts], False
|
| 193 |
+
texts.append(m.group(2).strip())
|
| 194 |
+
return texts, True
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def render_options(texts):
|
| 198 |
+
return "\n".join(f"{LETTERS[i]}. {t}" for i, t in enumerate(texts))
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def item_text(question, options):
|
| 202 |
+
"""Text embedded for the near-duplicate check: question + options."""
|
| 203 |
+
q = " ".join(str(question or "").split())
|
| 204 |
+
if isinstance(options, list) and options:
|
| 205 |
+
return q + "\n" + "\n".join(str(o) for o in options)
|
| 206 |
+
return q
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def permutations_for(item_id, k, n_perm=N_PERM, seed=SEED):
|
| 210 |
+
"""TASK.md step 1: n_perm option shuffles, seed 42, per item. perm[j] = original
|
| 211 |
+
option index shown at position j."""
|
| 212 |
+
rng = random.Random(f"{seed}|{item_id}")
|
| 213 |
+
return [rng.sample(range(k), k) for _ in range(n_perm)]
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# ------------------------------------------------------------------ log-probs
|
| 217 |
+
def letter_logprobs(top_logprobs, k):
|
| 218 |
+
"""top_logprobs: list of {token, logprob} for the first generated position.
|
| 219 |
+
-> (lp list over the k presented letters, missing letters, matched variants).
|
| 220 |
+
Tokenization variants ('A', ' A', '(A', 'A.') are merged by log-sum-exp."""
|
| 221 |
+
acc = {}
|
| 222 |
+
variants = {}
|
| 223 |
+
for e in top_logprobs or []:
|
| 224 |
+
m = _TOKEN_LETTER.match(e.get("token") or "")
|
| 225 |
+
if not m:
|
| 226 |
+
continue
|
| 227 |
+
L = m.group(1)
|
| 228 |
+
if L not in acc:
|
| 229 |
+
acc[L] = e["logprob"]
|
| 230 |
+
else:
|
| 231 |
+
a, b = acc[L], e["logprob"]
|
| 232 |
+
acc[L] = max(a, b) + math.log1p(math.exp(-abs(a - b)))
|
| 233 |
+
variants.setdefault(L, []).append(e.get("token"))
|
| 234 |
+
lp, missing = [], []
|
| 235 |
+
for i in range(k):
|
| 236 |
+
L = LETTERS[i]
|
| 237 |
+
if L in acc:
|
| 238 |
+
lp.append(float(acc[L]))
|
| 239 |
+
else:
|
| 240 |
+
lp.append(LP_FLOOR)
|
| 241 |
+
missing.append(L)
|
| 242 |
+
return lp, missing, variants
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def margin_of(lp, correct_pos):
|
| 246 |
+
others = [v for i, v in enumerate(lp) if i != correct_pos]
|
| 247 |
+
return lp[correct_pos] - (sum(others) / len(others) if others else 0.0)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def argmax_pos(lp):
|
| 251 |
+
best = max(lp)
|
| 252 |
+
return lp.index(best)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class ContextTooLong(Exception):
|
| 256 |
+
pass
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def logprob_request(endpoint, model, prompt, images_b64=None, timeout=(10, 600)):
|
| 260 |
+
"""One forward: max_tokens=1, logprobs=true, top_logprobs=20; the assistant turn is
|
| 261 |
+
prefilled with ASSISTANT_PREFIX (continue_final_message) so the next token is the
|
| 262 |
+
letter. -> dict(top=[{token, logprob}], top1_token, prompt_tokens, latency_s)."""
|
| 263 |
+
import requests
|
| 264 |
+
content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + b}}
|
| 265 |
+
for b in (images_b64 or [])]
|
| 266 |
+
content.append({"type": "text", "text": prompt})
|
| 267 |
+
body = {"model": model, "temperature": 0.0, "max_tokens": 1,
|
| 268 |
+
"logprobs": True, "top_logprobs": TOP_LOGPROBS,
|
| 269 |
+
"messages": [{"role": "user", "content": content},
|
| 270 |
+
{"role": "assistant", "content": ASSISTANT_PREFIX}],
|
| 271 |
+
"continue_final_message": True, "add_generation_prompt": False}
|
| 272 |
+
t0 = time.time()
|
| 273 |
+
r = requests.post(f"{endpoint}/chat/completions", json=body, timeout=timeout)
|
| 274 |
+
if r.status_code == 400 and ("maximum" in r.text or "longer than" in r.text
|
| 275 |
+
or "context length" in r.text):
|
| 276 |
+
raise ContextTooLong(r.text[:200])
|
| 277 |
+
r.raise_for_status()
|
| 278 |
+
d = r.json()
|
| 279 |
+
ch = d["choices"][0]
|
| 280 |
+
lpc = (ch.get("logprobs") or {}).get("content") or []
|
| 281 |
+
if not lpc:
|
| 282 |
+
raise RuntimeError("no logprobs in response")
|
| 283 |
+
top = [{"token": e.get("token"), "logprob": e.get("logprob")} for e in (lpc[0].get("top_logprobs") or [])]
|
| 284 |
+
return dict(top=top, top1_token=lpc[0].get("token"),
|
| 285 |
+
prompt_tokens=(d.get("usage") or {}).get("prompt_tokens", 0),
|
| 286 |
+
latency_s=round(time.time() - t0, 4))
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# ------------------------------------------------------------------ result files
|
| 290 |
+
def bench_files(step, bench):
|
| 291 |
+
"""All jsonl files of a benchmark under step<k>/ (part files included)."""
|
| 292 |
+
d = STEP_DIR[step]
|
| 293 |
+
if not os.path.isdir(d):
|
| 294 |
+
return []
|
| 295 |
+
out = []
|
| 296 |
+
for f in os.listdir(d):
|
| 297 |
+
if f == f"{bench}.jsonl" or (f.startswith(f"{bench}.p") and f.endswith(".jsonl")
|
| 298 |
+
and f[len(bench) + 2:-6].isdigit()):
|
| 299 |
+
out.append(os.path.join(d, f))
|
| 300 |
+
return sorted(out)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def unit_file(step, bench, part, n_parts):
|
| 304 |
+
return os.path.join(STEP_DIR[step], f"{bench}.jsonl" if n_parts == 1 else f"{bench}.p{part}.jsonl")
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def load_step_rows(step, benches=None):
|
| 308 |
+
"""item_id -> last successful row; plus item_id -> error count.
|
| 309 |
+
Rows with status != ok are errors (never counted as done)."""
|
| 310 |
+
ok, errs = {}, {}
|
| 311 |
+
d = STEP_DIR[step]
|
| 312 |
+
if not os.path.isdir(d):
|
| 313 |
+
return ok, errs
|
| 314 |
+
files = []
|
| 315 |
+
for f in sorted(os.listdir(d)):
|
| 316 |
+
if not f.endswith(".jsonl"):
|
| 317 |
+
continue
|
| 318 |
+
if benches is not None:
|
| 319 |
+
b = f[:-6]
|
| 320 |
+
if "." in b and b.rsplit(".", 1)[1][1:].isdigit() and b.rsplit(".", 1)[1].startswith("p"):
|
| 321 |
+
b = b.rsplit(".", 1)[0]
|
| 322 |
+
if b not in benches:
|
| 323 |
+
continue
|
| 324 |
+
files.append(os.path.join(d, f))
|
| 325 |
+
for p in files:
|
| 326 |
+
for r in read_jsonl(p):
|
| 327 |
+
iid = r.get("item_id")
|
| 328 |
+
if iid is None:
|
| 329 |
+
continue
|
| 330 |
+
if r.get("status", "ok") == "ok":
|
| 331 |
+
ok[iid] = r
|
| 332 |
+
else:
|
| 333 |
+
errs[iid] = errs.get(iid, 0) + 1
|
| 334 |
+
return ok, errs
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def append_rows(path, rows):
|
| 338 |
+
"""Append json rows under an exclusive flock (several array tasks may touch a file
|
| 339 |
+
across re-runs; the lock keeps rows whole)."""
|
| 340 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 341 |
+
data = "".join(json.dumps(r, ensure_ascii=False, default=str) + "\n" for r in rows)
|
| 342 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 343 |
+
fcntl.flock(f, fcntl.LOCK_EX)
|
| 344 |
+
try:
|
| 345 |
+
f.write(data)
|
| 346 |
+
f.flush()
|
| 347 |
+
finally:
|
| 348 |
+
fcntl.flock(f, fcntl.LOCK_UN)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# ------------------------------------------------------------------ sharding
|
| 352 |
+
def plan_units(work, max_unit=20000):
|
| 353 |
+
"""work: list of (bench, [item_ids sorted]) -> units [(bench, part, n_parts, ids)].
|
| 354 |
+
Big benchmarks are split into parts of <= max_unit items (deterministic by sorted
|
| 355 |
+
item_id) so one array task never owns more than max_unit items of one file."""
|
| 356 |
+
units = []
|
| 357 |
+
for bench, ids in work:
|
| 358 |
+
ids = sorted(ids)
|
| 359 |
+
n_parts = max(1, math.ceil(len(ids) / max_unit)) if ids else 1
|
| 360 |
+
size = math.ceil(len(ids) / n_parts) if ids else 0
|
| 361 |
+
for part in range(n_parts):
|
| 362 |
+
units.append((bench, part, n_parts, ids[part * size:(part + 1) * size]))
|
| 363 |
+
return units
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def assign_units(units, n_tasks, task_id, weight=lambda u: len(u[3])):
|
| 367 |
+
"""Deterministic LPT (largest first to the least loaded task)."""
|
| 368 |
+
loads = [0.0] * n_tasks
|
| 369 |
+
mine = []
|
| 370 |
+
for u in sorted(units, key=lambda u: (-weight(u), u[0], u[1])):
|
| 371 |
+
t = min(range(n_tasks), key=lambda i: (loads[i], i))
|
| 372 |
+
loads[t] += weight(u)
|
| 373 |
+
if t == task_id:
|
| 374 |
+
mine.append(u)
|
| 375 |
+
return mine, loads
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def slurm_task():
|
| 379 |
+
"""(task_id, n_tasks) from the Slurm array environment; (0, 1) outside Slurm."""
|
| 380 |
+
tid = int(os.environ.get("SLURM_ARRAY_TASK_ID", 0))
|
| 381 |
+
n = os.environ.get("SLURM_ARRAY_TASK_COUNT")
|
| 382 |
+
if n is None:
|
| 383 |
+
lo, hi = os.environ.get("SLURM_ARRAY_TASK_MIN"), os.environ.get("SLURM_ARRAY_TASK_MAX")
|
| 384 |
+
n = int(hi) - int(lo) + 1 if lo is not None and hi is not None else 1
|
| 385 |
+
if lo is not None:
|
| 386 |
+
tid -= int(lo)
|
| 387 |
+
return tid, int(n)
|