File size: 6,067 Bytes
f65907b | 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 | import os
import argparse
import glob
import shutil
import time
import numpy as np
from tensorboard.backend.event_processing import event_accumulator
def get_latest_event_file(log_root):
"""Recursively find the latest TensorBoard event file under log_root."""
event_files = glob.glob(os.path.join(log_root, "**", "events.out.tfevents.*"), recursive=True)
if not event_files:
raise RuntimeError(f"No TensorBoard event files found under {log_root}")
return max(event_files, key=os.path.getmtime)
def load_scalar(event_file, tag="loss"):
ea = event_accumulator.EventAccumulator(event_file)
ea.Reload()
if tag not in ea.Tags()["scalars"]:
raise RuntimeError(f"Tag '{tag}' not found in {event_file}. Available: {ea.Tags()['scalars']}")
events = ea.Scalars(tag)
steps = [e.step for e in events]
values = [e.value for e in events]
return np.array(steps), np.array(values)
def smooth(values, weight=0.9):
smoothed = []
last = values[0]
for val in values:
last = last * weight + (1 - weight) * val
smoothed.append(last)
return np.array(smoothed)
def preview_file_lines(file_path, max_chars=50):
"""Return number of lines and a list of truncated lines for preview."""
with open(file_path, "r", encoding="utf-8") as f:
lines = [line.rstrip("\n") for line in f.readlines()]
n_lines = len(lines)
truncated_lines = [line if len(line) <= max_chars else line[:max_chars] + "…" for line in lines]
if n_lines == 0:
truncated_lines = ["<empty>"]
return n_lines, truncated_lines
def main():
parser = argparse.ArgumentParser(description="Monitor TensorBoard logs and update prompt.txt when loss threshold is reached")
parser.add_argument("--log_root", type=str, required=True, help="Root folder containing TensorBoard logs (nested allowed)")
parser.add_argument("--sample_folder", type=str, required=True, help="Folder with prompt.txt and payload file")
parser.add_argument("--tag", type=str, default="loss/average", help="Scalar tag to monitor (default: loss)")
parser.add_argument("--threshold", type=float, required=True, help="Loss threshold to trigger prompt update")
parser.add_argument("--smoothing", type=float, default=0.9, help="Exponential smoothing weight (0-1, default 0.9)")
parser.add_argument("--poll_interval", type=int, default=10, help="Seconds between polling for new logs (default 10)")
parser.add_argument("--archive", action="store_true",
help="Pre-step: move contents of prompt.txt → prompt_payload.txt and empty prompt.txt. Must be only .txt file.")
args = parser.parse_args()
# Ensure sample folder exists
if not os.path.isdir(args.sample_folder):
raise RuntimeError(f"Sample folder does not exist: {args.sample_folder}")
# Ensure prompt.txt exists
prompt_file = os.path.join(args.sample_folder, "prompt.txt")
if not os.path.exists(prompt_file):
with open(prompt_file, "w", encoding="utf-8") as f:
f.write("")
# --- Pre-step: Archive prompt.txt contents if flag is set ---
if args.archive:
txt_files = glob.glob(os.path.join(args.sample_folder, "*.txt"))
if len(txt_files) != 1 or not txt_files[0].endswith("prompt.txt"):
raise RuntimeError("Archive mode requires prompt.txt to be the ONLY .txt file in the sample folder.")
archive_file = os.path.join(args.sample_folder, "prompt_payload.txt")
with open(prompt_file, "r", encoding="utf-8") as f:
contents = f.read()
with open(archive_file, "w", encoding="utf-8") as f:
f.write(contents)
# Empty out prompt.txt
with open(prompt_file, "w", encoding="utf-8") as f:
f.write("")
print(f"[ARCHIVE] Moved contents of {prompt_file} → {archive_file} and emptied {prompt_file}")
# Find payload file (any txt besides prompt.txt)
txt_files = [f for f in glob.glob(os.path.join(args.sample_folder, "*.txt")) if not f.endswith("prompt.txt")]
if not txt_files:
raise RuntimeError("No payload file found in sample folder (need one .txt besides prompt.txt).")
payload_file = txt_files[0]
# Startup preview
prompt_lines, prompt_preview_lines = preview_file_lines(prompt_file)
payload_lines, payload_preview_lines = preview_file_lines(payload_file)
print("=== Startup Info ===")
print(f"Prompt file: {prompt_file}")
print(f" Lines: {prompt_lines}")
print(f" Preview:")
for line in prompt_preview_lines:
print(f" {line}")
print(f"Payload file: {payload_file}")
print(f" Lines: {payload_lines}")
print(f" Preview:")
for line in payload_preview_lines:
print(f" {line}")
print("===================")
# Find latest event file (nested)
event_file = get_latest_event_file(args.log_root)
print(f"[INFO] Monitoring event file: {event_file}")
last_reported_step = -1
while True:
try:
steps, values = load_scalar(event_file, args.tag)
if len(values) == 0:
time.sleep(args.poll_interval)
continue
smoothed_values = smooth(values, args.smoothing)
# Check every 50 steps
for step, loss in zip(steps, smoothed_values):
if step % 50 == 0 and step > last_reported_step:
last_reported_step = step
triggered = loss < args.threshold
status = "TRIGGERED" if triggered else "not triggered"
print(f"[Step {step}] Smoothed loss={loss:.4f} -> {status}")
if triggered:
shutil.copy(payload_file, prompt_file)
print(f"[EXIT] Copied payload ({os.path.basename(payload_file)}) → prompt.txt")
return
except Exception as e:
print(f"[WARN] Error reading log: {e}")
time.sleep(args.poll_interval)
if __name__ == "__main__":
main()
|