Spaces:
Paused
Paused
Commit ·
dda4654
1
Parent(s): d8bb03f
training: add local run script and generated local summaries
Browse filesInclude the new local training entrypoint and its latest output summaries so HF Space has the same local-run artifacts available for debugging and comparison.
Made-with: Cursor
- plots/train_local_log.jsonl +1 -0
- plots/train_local_summary.json +26 -0
- training/train_local.py +251 -0
plots/train_local_log.jsonl
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"day": 1, "task": "monthly_engage", "seed": 42, "prompt": "Day: Mon | days_elapsed=0\nEnergy: 1.00 | Followers: 10000\nEngagement: 0.000 | Queue: 0\nCOACH HINT: post 2-3 times today at hours 19:00, 20:00, 14:00. Set scheduled_actions[i].hour to one of these.\nPlan today's actions (JSON only):", "response": "{\n \"tool_calls\": [],\n \"scheduled_actions\": [\n { \"hour\": 19, \"action_type\": \"post\", \"content_type\": \"reel\", \"topic\": \"Tech News Highlights\", \"tags\": [\"tech\", \"news\"], \"intent\": \"send_bait\" },\n { \"hour\": 20, \"action_type\": \"post\", \"content_type\": \"story\", \"topic\": \"Daily Tech Tips\", \"tags\": [\"tech\", \"tips\"], \"intent\": \"watch_bait\" },\n { \"hour\": 14, \"action_type\": \"post\", \"content_type\": \"text_post\", \"topic\": \"Tech Breakthroughs This Week\", \"tags\": [\"tech\", \"breakthroughs\"], \"intent\": \"like_bait\" }\n ],\n \"notes\": \"Scheduled posts at optimal engagement times to boost visibility and interaction.\"\n}"}
|
plots/train_local_summary.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"config": {
|
| 3 |
+
"task_horizon": 1,
|
| 4 |
+
"num_episodes": 1,
|
| 5 |
+
"num_rounds": 1,
|
| 6 |
+
"model": "qwen2.5:3b-instruct-q4_K_M",
|
| 7 |
+
"task": "monthly_engage",
|
| 8 |
+
"temperature": 0.7
|
| 9 |
+
},
|
| 10 |
+
"results": [
|
| 11 |
+
{
|
| 12 |
+
"round": 1,
|
| 13 |
+
"ep": 1,
|
| 14 |
+
"task": "monthly_engage",
|
| 15 |
+
"seed": 42,
|
| 16 |
+
"grader_score": 1.0,
|
| 17 |
+
"total_reward": 0.244,
|
| 18 |
+
"rewards": [
|
| 19 |
+
0.244
|
| 20 |
+
],
|
| 21 |
+
"final_energy": 1.0,
|
| 22 |
+
"follower_delta": 401
|
| 23 |
+
}
|
| 24 |
+
],
|
| 25 |
+
"elapsed_seconds": 7.4
|
| 26 |
+
}
|
training/train_local.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
cd viral-posts-env
|
| 7 |
+
.venv/bin/python training/train_local.py
|
| 8 |
+
|
| 9 |
+
Override via env:
|
| 10 |
+
TASK_HORIZON=1 # days per episode
|
| 11 |
+
NUM_EPISODES=1 # episodes per round
|
| 12 |
+
NUM_ROUNDS=1 # outer loop
|
| 13 |
+
OLLAMA_MODEL=qwen2.5:3b-instruct-q4_K_M
|
| 14 |
+
TASK=monthly_engage # or monthly_strategic / monthly_competitive
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
+
import textwrap
|
| 22 |
+
import time
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
os.environ.setdefault("TASK_HORIZON", "1")
|
| 26 |
+
|
| 27 |
+
REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 28 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 29 |
+
|
| 30 |
+
import httpx # noqa: E402
|
| 31 |
+
|
| 32 |
+
from models import ScheduledAction, ToolCall, ViraltestAction # noqa: E402
|
| 33 |
+
from server.viraltest_environment import ( # noqa: E402
|
| 34 |
+
TASK_HORIZON,
|
| 35 |
+
ViraltestEnvironment,
|
| 36 |
+
get_peak_hours,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
NUM_EPISODES = int(os.environ.get("NUM_EPISODES", "1"))
|
| 40 |
+
NUM_ROUNDS = int(os.environ.get("NUM_ROUNDS", "1"))
|
| 41 |
+
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen2.5:3b-instruct-q4_K_M")
|
| 42 |
+
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434")
|
| 43 |
+
TASK = os.environ.get("TASK", "monthly_engage")
|
| 44 |
+
SEED = int(os.environ.get("SEED", "42"))
|
| 45 |
+
TEMPERATURE = float(os.environ.get("TEMPERATURE", "0.7"))
|
| 46 |
+
|
| 47 |
+
OUT_DIR = REPO_ROOT / "plots"
|
| 48 |
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
LOG_PATH = OUT_DIR / "train_local_log.jsonl"
|
| 50 |
+
|
| 51 |
+
print(f"[config] task_horizon={TASK_HORIZON} episodes={NUM_EPISODES} rounds={NUM_ROUNDS} "
|
| 52 |
+
f"task={TASK} model={OLLAMA_MODEL}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
SYSTEM_PROMPT = textwrap.dedent("""\
|
| 56 |
+
You are an Instagram content strategy agent. Each step is one day.
|
| 57 |
+
|
| 58 |
+
RESPONSE FORMAT — return ONLY valid JSON, no markdown:
|
| 59 |
+
{
|
| 60 |
+
"tool_calls": [{"name": "<tool>", "arguments": {...}}],
|
| 61 |
+
"scheduled_actions": [
|
| 62 |
+
{"hour": 0-23, "action_type": "post|create_content",
|
| 63 |
+
"content_type": "reel|story|carousel|text_post",
|
| 64 |
+
"topic": "<string>", "tags": ["..."],
|
| 65 |
+
"intent": "send_bait|save_bait|watch_bait|like_bait"}
|
| 66 |
+
],
|
| 67 |
+
"notes": "strategy notes"
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
VALID TOOL ARGS:
|
| 71 |
+
- niche: tech | lifestyle | fitness | business | food | travel | fashion | beauty | photography | education
|
| 72 |
+
- segment_id: young_professionals | students | parents | global_night_owls | passive_scrollers
|
| 73 |
+
- competitor_id: niche_expert | viral_chaser | lifestyle_blogger | b2b_thought_leader | food_creator | fitness_coach | travel_creator
|
| 74 |
+
|
| 75 |
+
POSTING RULES:
|
| 76 |
+
- Active day: 2-3 `post` actions at peak hours.
|
| 77 |
+
- Vary `intent` and `content_type`.""")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
_DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def format_obs(obs, hint_hours: str | None = None) -> str:
|
| 84 |
+
day_name = _DAY_NAMES[obs.day_of_week] if 0 <= obs.day_of_week < 7 else "?"
|
| 85 |
+
sig = getattr(obs, "engagement_signals", None)
|
| 86 |
+
sig_str = ""
|
| 87 |
+
if sig:
|
| 88 |
+
sig_str = (f"Signals: watch={sig.watch_time:.3f} "
|
| 89 |
+
f"sends={sig.sends_per_reach:.3f} saves={sig.saves:.3f}\n")
|
| 90 |
+
hint = ""
|
| 91 |
+
if hint_hours:
|
| 92 |
+
hint = (f"COACH HINT: post 2-3 times today at hours {hint_hours}. "
|
| 93 |
+
"Set scheduled_actions[i].hour to one of these.\n")
|
| 94 |
+
return (f"Day: {day_name} | days_elapsed={obs.days_elapsed}\n"
|
| 95 |
+
f"Energy: {obs.creator_energy:.2f} | Followers: {obs.follower_count}\n"
|
| 96 |
+
f"Engagement: {obs.engagement_rate:.3f} | Queue: {obs.content_queue_size}\n"
|
| 97 |
+
f"{sig_str}{hint}Plan today's actions (JSON only):")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def parse_model_output(text: str) -> ViraltestAction:
|
| 101 |
+
text = text.strip()
|
| 102 |
+
if "```" in text:
|
| 103 |
+
text = "\n".join(l for l in text.split("\n") if not l.strip().startswith("```")).strip()
|
| 104 |
+
s, e = text.find("{"), text.rfind("}") + 1
|
| 105 |
+
if s >= 0 and e > s:
|
| 106 |
+
text = text[s:e]
|
| 107 |
+
try:
|
| 108 |
+
data = json.loads(text)
|
| 109 |
+
except Exception:
|
| 110 |
+
return ViraltestAction(scheduled_actions=[])
|
| 111 |
+
tool_calls = []
|
| 112 |
+
for tc in data.get("tool_calls", []):
|
| 113 |
+
if not isinstance(tc, dict) or "name" not in tc:
|
| 114 |
+
continue
|
| 115 |
+
args = tc.get("arguments", {})
|
| 116 |
+
if isinstance(args, list) and args and isinstance(args[0], dict):
|
| 117 |
+
args = args[0]
|
| 118 |
+
if isinstance(args, dict):
|
| 119 |
+
try:
|
| 120 |
+
tool_calls.append(ToolCall(name=tc["name"], arguments=args))
|
| 121 |
+
except Exception:
|
| 122 |
+
pass
|
| 123 |
+
scheduled = []
|
| 124 |
+
for a in data.get("scheduled_actions", []):
|
| 125 |
+
try:
|
| 126 |
+
scheduled.append(ScheduledAction(**a))
|
| 127 |
+
except Exception:
|
| 128 |
+
pass
|
| 129 |
+
return ViraltestAction(tool_calls=tool_calls, scheduled_actions=scheduled,
|
| 130 |
+
notes=data.get("notes"))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def ollama_generate(prompt: str, temperature: float = 0.7, num_predict: int = 384) -> str:
|
| 134 |
+
try:
|
| 135 |
+
resp = httpx.post(
|
| 136 |
+
f"{OLLAMA_URL}/api/generate",
|
| 137 |
+
json={
|
| 138 |
+
"model": OLLAMA_MODEL,
|
| 139 |
+
"prompt": prompt,
|
| 140 |
+
"system": SYSTEM_PROMPT,
|
| 141 |
+
"stream": False,
|
| 142 |
+
"options": {"temperature": temperature, "num_predict": num_predict},
|
| 143 |
+
},
|
| 144 |
+
timeout=120.0,
|
| 145 |
+
)
|
| 146 |
+
resp.raise_for_status()
|
| 147 |
+
return resp.json().get("response", "")
|
| 148 |
+
except Exception as e:
|
| 149 |
+
print(f" [ollama-error] {type(e).__name__}: {e}")
|
| 150 |
+
return '{"scheduled_actions": []}'
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def run_one_episode(task: str, seed: int, log_fp) -> dict:
|
| 154 |
+
env = ViraltestEnvironment()
|
| 155 |
+
obs = env.reset(task=task, seed=seed)
|
| 156 |
+
rewards: list[float] = []
|
| 157 |
+
pairs: list[dict] = []
|
| 158 |
+
for day in range(1, TASK_HORIZON + 1):
|
| 159 |
+
if obs.done:
|
| 160 |
+
break
|
| 161 |
+
peak = get_peak_hours(obs.day_of_week, top_k=3)
|
| 162 |
+
hint = ", ".join(f"{h:02d}:00" for h in peak) if peak else None
|
| 163 |
+
prompt = format_obs(obs, hint_hours=hint)
|
| 164 |
+
t = time.time()
|
| 165 |
+
response = ollama_generate(prompt, temperature=TEMPERATURE)
|
| 166 |
+
gen_s = time.time() - t
|
| 167 |
+
action = parse_model_output(response)
|
| 168 |
+
log_fp.write(json.dumps({
|
| 169 |
+
"day": day, "task": task, "seed": seed,
|
| 170 |
+
"prompt": prompt, "response": response,
|
| 171 |
+
}) + "\n")
|
| 172 |
+
log_fp.flush()
|
| 173 |
+
obs = env.step(action)
|
| 174 |
+
r = obs.reward or 0.0
|
| 175 |
+
rewards.append(r)
|
| 176 |
+
n_posts = sum(1 for sa in action.scheduled_actions if sa.action_type == "post")
|
| 177 |
+
n_tools = len(action.tool_calls)
|
| 178 |
+
print(f" day {day}: gen={gen_s:.1f}s posts={n_posts} tools={n_tools} "
|
| 179 |
+
f"reward={r:.4f} energy={obs.creator_energy:.2f}")
|
| 180 |
+
pairs.append({"prompt": prompt, "response": response, "reward": r})
|
| 181 |
+
grader = (obs.metadata or {}).get("grader_score", 0.0)
|
| 182 |
+
return {
|
| 183 |
+
"task": task, "seed": seed,
|
| 184 |
+
"grader_score": grader,
|
| 185 |
+
"total_reward": sum(rewards),
|
| 186 |
+
"rewards": rewards,
|
| 187 |
+
"final_energy": obs.creator_energy,
|
| 188 |
+
"follower_delta": obs.follower_count - 10000,
|
| 189 |
+
"pairs": pairs,
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def main() -> None:
|
| 194 |
+
t_start = time.time()
|
| 195 |
+
try:
|
| 196 |
+
info = httpx.get(f"{OLLAMA_URL}/api/tags", timeout=5).json()
|
| 197 |
+
names = [m["name"] for m in info.get("models", [])]
|
| 198 |
+
print(f"[ollama] reachable. models: {names}")
|
| 199 |
+
if OLLAMA_MODEL not in names:
|
| 200 |
+
print(f" WARNING: {OLLAMA_MODEL} not in {names}. "
|
| 201 |
+
f"Run: ollama pull {OLLAMA_MODEL}")
|
| 202 |
+
except Exception as e:
|
| 203 |
+
print(f"[ollama] NOT reachable at {OLLAMA_URL}: {e}\n Start it with: ollama serve")
|
| 204 |
+
sys.exit(1)
|
| 205 |
+
|
| 206 |
+
LOG_PATH.write_text("")
|
| 207 |
+
log_fp = LOG_PATH.open("a")
|
| 208 |
+
|
| 209 |
+
all_results: list[dict] = []
|
| 210 |
+
for round_idx in range(NUM_ROUNDS):
|
| 211 |
+
print(f"\n[round] {round_idx + 1}/{NUM_ROUNDS}")
|
| 212 |
+
for ep in range(NUM_EPISODES):
|
| 213 |
+
seed = SEED + ep + round_idx * 100
|
| 214 |
+
print(f" [episode] {ep + 1}/{NUM_EPISODES} task={TASK} seed={seed}")
|
| 215 |
+
t_ep = time.time()
|
| 216 |
+
result = run_one_episode(TASK, seed, log_fp)
|
| 217 |
+
all_results.append({"round": round_idx + 1, "ep": ep + 1, **result})
|
| 218 |
+
print(f" -> grader={result['grader_score']:.4f} "
|
| 219 |
+
f"reward={result['total_reward']:.3f} "
|
| 220 |
+
f"energy={result['final_energy']:.2f} "
|
| 221 |
+
f"({time.time() - t_ep:.1f}s)")
|
| 222 |
+
|
| 223 |
+
log_fp.close()
|
| 224 |
+
|
| 225 |
+
summary = {
|
| 226 |
+
"config": {
|
| 227 |
+
"task_horizon": TASK_HORIZON,
|
| 228 |
+
"num_episodes": NUM_EPISODES,
|
| 229 |
+
"num_rounds": NUM_ROUNDS,
|
| 230 |
+
"model": OLLAMA_MODEL,
|
| 231 |
+
"task": TASK,
|
| 232 |
+
"temperature": TEMPERATURE,
|
| 233 |
+
},
|
| 234 |
+
"results": [
|
| 235 |
+
{k: v for k, v in r.items() if k != "pairs"} for r in all_results
|
| 236 |
+
],
|
| 237 |
+
"elapsed_seconds": round(time.time() - t_start, 1),
|
| 238 |
+
}
|
| 239 |
+
summary_path = OUT_DIR / "train_local_summary.json"
|
| 240 |
+
summary_path.write_text(json.dumps(summary, indent=2))
|
| 241 |
+
print(f"\n[summary] -> {summary_path}")
|
| 242 |
+
print(f"[log] -> {LOG_PATH}")
|
| 243 |
+
print(f"[done] {time.time() - t_start:.1f}s total")
|
| 244 |
+
print("\nResults:")
|
| 245 |
+
for r in all_results:
|
| 246 |
+
print(f" round={r['round']} ep={r['ep']} task={r['task']} "
|
| 247 |
+
f"grader={r['grader_score']:.4f} reward={r['total_reward']:.3f}")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
if __name__ == "__main__":
|
| 251 |
+
main()
|