Datasets:
File size: 5,240 Bytes
248b46c | 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 | #!/usr/bin/env python3
import argparse
import json
from collections import Counter
from pathlib import Path
import numpy as np
def parse_args():
p = argparse.ArgumentParser(description="Extract per-expert windows from a continuous GPT-OSS trace")
p.add_argument("--run-dir", required=True)
p.add_argument("--output-root", required=True)
p.add_argument("--layer-idx", type=int, default=0)
p.add_argument("--phase", default="decode")
p.add_argument("--trace-domain", choices=["raw", "resampled"], default="resampled")
p.add_argument("--pad-before", type=int, default=0, help="padding in resampled samples")
p.add_argument("--pad-after", type=int, default=0, help="padding in resampled samples")
p.add_argument("--min-samples", type=int, default=16)
return p.parse_args()
def raw_to_resampled_start(raw_idx: int, raw_len: int, resampled_len: int) -> int:
if raw_len <= 1 or resampled_len <= 1:
return 0
return int(np.floor(float(raw_idx) * float(resampled_len - 1) / float(raw_len - 1)))
def raw_to_resampled_end(raw_idx: int, raw_len: int, resampled_len: int) -> int:
if raw_len <= 1 or resampled_len <= 1:
return 1
return int(np.ceil(float(raw_idx) * float(resampled_len - 1) / float(raw_len - 1)))
def main():
args = parse_args()
run_dir = Path(args.run_dir).expanduser().resolve()
output_root = Path(args.output_root).expanduser().resolve()
output_root.mkdir(parents=True, exist_ok=True)
meta = json.loads((run_dir / "capture_meta.json").read_text())
timeline = json.loads((run_dir / "timeline.json").read_text())
trace_path = run_dir / ("trace.npy" if str(args.trace_domain) == "raw" else "trace_resampled.npy")
trace = np.load(trace_path, mmap_mode="r")
raw_len = int(meta["raw_trace_len"])
trace_len = int(trace.shape[0])
starts = {}
counts = Counter()
durations = []
records = []
for ev in timeline:
if str(ev.get("phase", "")) != str(args.phase):
continue
layer_val = ev.get("layer_idx")
if layer_val is None:
continue
if int(layer_val) != int(args.layer_idx):
continue
name = str(ev.get("name"))
if name == "expert_start":
key = (int(ev["decode_step_idx"]), int(ev["expert_idx"]))
starts[key] = int(ev["trace_sample_index"])
continue
if name != "expert_end":
continue
key = (int(ev["decode_step_idx"]), int(ev["expert_idx"]))
if key not in starts:
continue
start_raw = int(starts.pop(key))
end_raw = int(ev["trace_sample_index"])
if str(args.trace_domain) == "raw":
start = max(0, int(start_raw) - int(args.pad_before))
end = min(trace_len, int(end_raw) + int(args.pad_after))
else:
start = max(0, raw_to_resampled_start(start_raw, raw_len, trace_len) - int(args.pad_before))
end = min(trace_len, raw_to_resampled_end(end_raw, raw_len, trace_len) + int(args.pad_after))
if end - start < int(args.min_samples):
continue
decode_step_idx, expert_idx = key
seg = np.asarray(trace[start:end], dtype=np.float32)
class_dir = output_root / f"expert_{expert_idx:02d}"
class_dir.mkdir(parents=True, exist_ok=True)
out_path = class_dir / f"step_{decode_step_idx:05d}.npy"
np.save(out_path, seg)
counts[expert_idx] += 1
durations.append(int(end - start))
records.append(
{
"phase": str(args.phase),
"layer_idx": int(args.layer_idx),
"decode_step_idx": int(decode_step_idx),
"expert_idx": int(expert_idx),
"start_raw": int(start_raw),
"end_raw": int(end_raw),
"start_resampled": int(start),
"end_resampled": int(end),
"samples": int(end - start),
"trace_file": str(out_path),
}
)
summary = {
"run_dir": str(run_dir),
"output_root": str(output_root),
"phase": str(args.phase),
"layer_idx": int(args.layer_idx),
"trace_domain": str(args.trace_domain),
"raw_trace_len": int(raw_len),
"trace_len": int(trace_len),
"pad_before": int(args.pad_before),
"pad_after": int(args.pad_after),
"min_samples": int(args.min_samples),
"num_segments": int(sum(counts.values())),
"class_counts": {f"expert_{k:02d}": int(v) for k, v in sorted(counts.items())},
"duration_mean": None if not durations else float(np.mean(durations)),
"duration_median": None if not durations else float(np.median(durations)),
"duration_min": None if not durations else int(np.min(durations)),
"duration_max": None if not durations else int(np.max(durations)),
}
(output_root / "extract_summary.json").write_text(json.dumps(summary, indent=2))
with (output_root / "extract_records.jsonl").open("w") as f:
for rec in records:
f.write(json.dumps(rec) + "\n")
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
|