Download prompt_morpher.py from sphenelabs/TrainingScripts: direct link, hf CLI and curl.
- Browser
- Download file 6.07 kB
-
https://huggingface.co/datasets/sphenelabs/TrainingScripts/resolve/main/prompt_morpher.py
- Command line
-
hf download hf://datasets/sphenelabs/TrainingScripts/prompt_morpher.py
-
curl -L -o prompt_morpher.py https://huggingface.co/datasets/sphenelabs/TrainingScripts/resolve/main/prompt_morpher.py
6.07 kB
| 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() | |