Create prompt_morpher.py
Browse files- prompt_morpher.py +142 -0
prompt_morpher.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import glob
|
| 4 |
+
import shutil
|
| 5 |
+
import time
|
| 6 |
+
import numpy as np
|
| 7 |
+
from tensorboard.backend.event_processing import event_accumulator
|
| 8 |
+
|
| 9 |
+
def get_latest_event_file(log_root):
|
| 10 |
+
"""Recursively find the latest TensorBoard event file under log_root."""
|
| 11 |
+
event_files = glob.glob(os.path.join(log_root, "**", "events.out.tfevents.*"), recursive=True)
|
| 12 |
+
if not event_files:
|
| 13 |
+
raise RuntimeError(f"No TensorBoard event files found under {log_root}")
|
| 14 |
+
return max(event_files, key=os.path.getmtime)
|
| 15 |
+
|
| 16 |
+
def load_scalar(event_file, tag="loss"):
|
| 17 |
+
ea = event_accumulator.EventAccumulator(event_file)
|
| 18 |
+
ea.Reload()
|
| 19 |
+
if tag not in ea.Tags()["scalars"]:
|
| 20 |
+
raise RuntimeError(f"Tag '{tag}' not found in {event_file}. Available: {ea.Tags()['scalars']}")
|
| 21 |
+
events = ea.Scalars(tag)
|
| 22 |
+
steps = [e.step for e in events]
|
| 23 |
+
values = [e.value for e in events]
|
| 24 |
+
return np.array(steps), np.array(values)
|
| 25 |
+
|
| 26 |
+
def smooth(values, weight=0.9):
|
| 27 |
+
smoothed = []
|
| 28 |
+
last = values[0]
|
| 29 |
+
for val in values:
|
| 30 |
+
last = last * weight + (1 - weight) * val
|
| 31 |
+
smoothed.append(last)
|
| 32 |
+
return np.array(smoothed)
|
| 33 |
+
|
| 34 |
+
def preview_file_lines(file_path, max_chars=50):
|
| 35 |
+
"""Return number of lines and a list of truncated lines for preview."""
|
| 36 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 37 |
+
lines = [line.rstrip("\n") for line in f.readlines()]
|
| 38 |
+
n_lines = len(lines)
|
| 39 |
+
truncated_lines = [line if len(line) <= max_chars else line[:max_chars] + "…" for line in lines]
|
| 40 |
+
if n_lines == 0:
|
| 41 |
+
truncated_lines = ["<empty>"]
|
| 42 |
+
return n_lines, truncated_lines
|
| 43 |
+
|
| 44 |
+
def main():
|
| 45 |
+
parser = argparse.ArgumentParser(description="Monitor TensorBoard logs and update prompt.txt when loss threshold is reached")
|
| 46 |
+
parser.add_argument("--log_root", type=str, required=True, help="Root folder containing TensorBoard logs (nested allowed)")
|
| 47 |
+
parser.add_argument("--sample_folder", type=str, required=True, help="Folder with prompt.txt and payload file")
|
| 48 |
+
parser.add_argument("--tag", type=str, default="loss/average", help="Scalar tag to monitor (default: loss)")
|
| 49 |
+
parser.add_argument("--threshold", type=float, required=True, help="Loss threshold to trigger prompt update")
|
| 50 |
+
parser.add_argument("--smoothing", type=float, default=0.9, help="Exponential smoothing weight (0-1, default 0.9)")
|
| 51 |
+
parser.add_argument("--poll_interval", type=int, default=10, help="Seconds between polling for new logs (default 10)")
|
| 52 |
+
parser.add_argument("--archive", action="store_true",
|
| 53 |
+
help="Pre-step: move contents of prompt.txt → prompt_payload.txt and empty prompt.txt. Must be only .txt file.")
|
| 54 |
+
args = parser.parse_args()
|
| 55 |
+
|
| 56 |
+
# Ensure sample folder exists
|
| 57 |
+
if not os.path.isdir(args.sample_folder):
|
| 58 |
+
raise RuntimeError(f"Sample folder does not exist: {args.sample_folder}")
|
| 59 |
+
|
| 60 |
+
# Ensure prompt.txt exists
|
| 61 |
+
prompt_file = os.path.join(args.sample_folder, "prompt.txt")
|
| 62 |
+
if not os.path.exists(prompt_file):
|
| 63 |
+
with open(prompt_file, "w", encoding="utf-8") as f:
|
| 64 |
+
f.write("")
|
| 65 |
+
|
| 66 |
+
# --- Pre-step: Archive prompt.txt contents if flag is set ---
|
| 67 |
+
if args.archive:
|
| 68 |
+
txt_files = glob.glob(os.path.join(args.sample_folder, "*.txt"))
|
| 69 |
+
if len(txt_files) != 1 or not txt_files[0].endswith("prompt.txt"):
|
| 70 |
+
raise RuntimeError("Archive mode requires prompt.txt to be the ONLY .txt file in the sample folder.")
|
| 71 |
+
|
| 72 |
+
archive_file = os.path.join(args.sample_folder, "prompt_payload.txt")
|
| 73 |
+
|
| 74 |
+
with open(prompt_file, "r", encoding="utf-8") as f:
|
| 75 |
+
contents = f.read()
|
| 76 |
+
|
| 77 |
+
with open(archive_file, "w", encoding="utf-8") as f:
|
| 78 |
+
f.write(contents)
|
| 79 |
+
|
| 80 |
+
# Empty out prompt.txt
|
| 81 |
+
with open(prompt_file, "w", encoding="utf-8") as f:
|
| 82 |
+
f.write("")
|
| 83 |
+
|
| 84 |
+
print(f"[ARCHIVE] Moved contents of {prompt_file} → {archive_file} and emptied {prompt_file}")
|
| 85 |
+
|
| 86 |
+
# Find payload file (any txt besides prompt.txt)
|
| 87 |
+
txt_files = [f for f in glob.glob(os.path.join(args.sample_folder, "*.txt")) if not f.endswith("prompt.txt")]
|
| 88 |
+
if not txt_files:
|
| 89 |
+
raise RuntimeError("No payload file found in sample folder (need one .txt besides prompt.txt).")
|
| 90 |
+
payload_file = txt_files[0]
|
| 91 |
+
|
| 92 |
+
# Startup preview
|
| 93 |
+
prompt_lines, prompt_preview_lines = preview_file_lines(prompt_file)
|
| 94 |
+
payload_lines, payload_preview_lines = preview_file_lines(payload_file)
|
| 95 |
+
|
| 96 |
+
print("=== Startup Info ===")
|
| 97 |
+
print(f"Prompt file: {prompt_file}")
|
| 98 |
+
print(f" Lines: {prompt_lines}")
|
| 99 |
+
print(f" Preview:")
|
| 100 |
+
for line in prompt_preview_lines:
|
| 101 |
+
print(f" {line}")
|
| 102 |
+
print(f"Payload file: {payload_file}")
|
| 103 |
+
print(f" Lines: {payload_lines}")
|
| 104 |
+
print(f" Preview:")
|
| 105 |
+
for line in payload_preview_lines:
|
| 106 |
+
print(f" {line}")
|
| 107 |
+
print("===================")
|
| 108 |
+
|
| 109 |
+
# Find latest event file (nested)
|
| 110 |
+
event_file = get_latest_event_file(args.log_root)
|
| 111 |
+
print(f"[INFO] Monitoring event file: {event_file}")
|
| 112 |
+
|
| 113 |
+
last_reported_step = -1
|
| 114 |
+
|
| 115 |
+
while True:
|
| 116 |
+
try:
|
| 117 |
+
steps, values = load_scalar(event_file, args.tag)
|
| 118 |
+
if len(values) == 0:
|
| 119 |
+
time.sleep(args.poll_interval)
|
| 120 |
+
continue
|
| 121 |
+
|
| 122 |
+
smoothed_values = smooth(values, args.smoothing)
|
| 123 |
+
|
| 124 |
+
# Check every 50 steps
|
| 125 |
+
for step, loss in zip(steps, smoothed_values):
|
| 126 |
+
if step % 50 == 0 and step > last_reported_step:
|
| 127 |
+
last_reported_step = step
|
| 128 |
+
triggered = loss < args.threshold
|
| 129 |
+
status = "TRIGGERED" if triggered else "not triggered"
|
| 130 |
+
print(f"[Step {step}] Smoothed loss={loss:.4f} -> {status}")
|
| 131 |
+
if triggered:
|
| 132 |
+
shutil.copy(payload_file, prompt_file)
|
| 133 |
+
print(f"[EXIT] Copied payload ({os.path.basename(payload_file)}) → prompt.txt")
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
print(f"[WARN] Error reading log: {e}")
|
| 138 |
+
|
| 139 |
+
time.sleep(args.poll_interval)
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
main()
|