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| 1 |
+
"""Collect supervised traces for FlowOS without GRPO."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import asyncio
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from .baseline import fallback_action
|
| 13 |
+
from .training_utils import (
|
| 14 |
+
TRAIN_SYSTEM_PROMPT,
|
| 15 |
+
build_episode_samples,
|
| 16 |
+
build_turn_prompt,
|
| 17 |
+
coerce_action,
|
| 18 |
+
format_action_text,
|
| 19 |
+
parse_sample_prompt,
|
| 20 |
+
persist_episode_artifacts,
|
| 21 |
+
samples_to_dataset_prompts,
|
| 22 |
+
)
|
| 23 |
+
from .client import DeveloperControlRoomEnv
|
| 24 |
+
except ImportError:
|
| 25 |
+
from baseline import fallback_action
|
| 26 |
+
from training_utils import (
|
| 27 |
+
TRAIN_SYSTEM_PROMPT,
|
| 28 |
+
build_episode_samples,
|
| 29 |
+
build_turn_prompt,
|
| 30 |
+
coerce_action,
|
| 31 |
+
format_action_text,
|
| 32 |
+
parse_sample_prompt,
|
| 33 |
+
persist_episode_artifacts,
|
| 34 |
+
samples_to_dataset_prompts,
|
| 35 |
+
)
|
| 36 |
+
from client import DeveloperControlRoomEnv
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def parse_args() -> argparse.Namespace:
|
| 40 |
+
parser = argparse.ArgumentParser(description="Collect fallback/teacher traces for FlowOS SFT")
|
| 41 |
+
parser.add_argument("--env-url", default="http://localhost:7860", help="FlowOS OpenEnv server URL")
|
| 42 |
+
parser.add_argument("--task-scope", default="all", help="Task scope: all or comma-separated task ids")
|
| 43 |
+
parser.add_argument("--dataset-size", type=int, default=8, help="Number of episodes to collect")
|
| 44 |
+
parser.add_argument("--max-turns", type=int, default=12, help="Max environment turns per episode")
|
| 45 |
+
parser.add_argument("--output-dir", default="outputs/sft_traces", help="Directory for JSONL traces")
|
| 46 |
+
parser.add_argument("--policy", default="fallback", choices=("fallback",), help="Teacher policy to use")
|
| 47 |
+
return parser.parse_args()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
async def collect_episode(
|
| 51 |
+
env_url: str,
|
| 52 |
+
sample_prompt: str,
|
| 53 |
+
max_turns: int,
|
| 54 |
+
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
| 55 |
+
sample = parse_sample_prompt(sample_prompt)
|
| 56 |
+
env = DeveloperControlRoomEnv(base_url=env_url)
|
| 57 |
+
await env.connect()
|
| 58 |
+
transcript: list[dict[str, Any]] = []
|
| 59 |
+
examples: list[dict[str, Any]] = []
|
| 60 |
+
try:
|
| 61 |
+
result = await env.reset(
|
| 62 |
+
task_id=sample.task_id,
|
| 63 |
+
scenario_index=sample.scenario_index,
|
| 64 |
+
seed=sample.seed,
|
| 65 |
+
)
|
| 66 |
+
observation = result.observation
|
| 67 |
+
|
| 68 |
+
for _ in range(max_turns):
|
| 69 |
+
if result.done:
|
| 70 |
+
break
|
| 71 |
+
prompt = build_turn_prompt(observation, transcript)
|
| 72 |
+
action_dict = fallback_action(sample.task_id, observation)
|
| 73 |
+
action = coerce_action(action_dict)
|
| 74 |
+
action_json = json.dumps(action_dict, separators=(",", ":"), ensure_ascii=False)
|
| 75 |
+
examples.append(
|
| 76 |
+
{
|
| 77 |
+
"task_id": sample.task_id,
|
| 78 |
+
"scenario_id": observation.scenario_id,
|
| 79 |
+
"episode_id": observation.episode_id,
|
| 80 |
+
"step": observation.step_count + 1,
|
| 81 |
+
"system_prompt": TRAIN_SYSTEM_PROMPT,
|
| 82 |
+
"user_prompt": prompt,
|
| 83 |
+
"target_action": action_json,
|
| 84 |
+
"action_type": action.action_type,
|
| 85 |
+
"editable_targets": observation.editable_targets,
|
| 86 |
+
"available_validators": observation.available_validators,
|
| 87 |
+
}
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
result = await env.step(action)
|
| 91 |
+
observation = result.observation
|
| 92 |
+
transcript.append(
|
| 93 |
+
{
|
| 94 |
+
"action_text": format_action_text(action),
|
| 95 |
+
"reward": float(result.reward or 0.0),
|
| 96 |
+
"feedback": observation.feedback,
|
| 97 |
+
"error": observation.last_action_error,
|
| 98 |
+
"raw_model_text": "",
|
| 99 |
+
}
|
| 100 |
+
)
|
| 101 |
+
if result.done:
|
| 102 |
+
break
|
| 103 |
+
|
| 104 |
+
metrics = {
|
| 105 |
+
"task_id": sample.task_id,
|
| 106 |
+
"scenario_id": observation.scenario_id,
|
| 107 |
+
"steps": len(transcript),
|
| 108 |
+
"materialized_artifacts": dict(getattr(observation, "materialized_artifacts", {})),
|
| 109 |
+
"runtime_status": dict(getattr(observation, "runtime_status", {})),
|
| 110 |
+
"output_schema": list(getattr(observation, "output_schema", [])),
|
| 111 |
+
"report_preview": list(getattr(observation, "report_preview", [])),
|
| 112 |
+
}
|
| 113 |
+
return examples, metrics
|
| 114 |
+
finally:
|
| 115 |
+
await env.close()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def main() -> None:
|
| 119 |
+
args = parse_args()
|
| 120 |
+
output_dir = Path(args.output_dir)
|
| 121 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
traces_path = output_dir / "traces.jsonl"
|
| 123 |
+
artifact_root = output_dir / "artifacts"
|
| 124 |
+
|
| 125 |
+
prompts = samples_to_dataset_prompts(build_episode_samples(args.task_scope, args.dataset_size))
|
| 126 |
+
|
| 127 |
+
all_examples: list[dict[str, Any]] = []
|
| 128 |
+
for prompt in prompts:
|
| 129 |
+
examples, metrics = asyncio.run(collect_episode(args.env_url, prompt, args.max_turns))
|
| 130 |
+
all_examples.extend(examples)
|
| 131 |
+
if metrics["materialized_artifacts"] or metrics["runtime_status"]:
|
| 132 |
+
class _Metrics:
|
| 133 |
+
def __init__(self, payload: dict[str, Any]) -> None:
|
| 134 |
+
self.task_id = payload["task_id"]
|
| 135 |
+
self.scenario_id = payload["scenario_id"]
|
| 136 |
+
self.steps = payload["steps"]
|
| 137 |
+
self.materialized_artifacts = payload["materialized_artifacts"]
|
| 138 |
+
self.runtime_status = payload["runtime_status"]
|
| 139 |
+
self.output_schema = payload["output_schema"]
|
| 140 |
+
self.report_preview = payload["report_preview"]
|
| 141 |
+
|
| 142 |
+
persist_episode_artifacts(artifact_root, _Metrics(metrics))
|
| 143 |
+
|
| 144 |
+
with traces_path.open("w", encoding="utf-8") as handle:
|
| 145 |
+
for row in all_examples:
|
| 146 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 147 |
+
|
| 148 |
+
print(f"Wrote {len(all_examples)} supervised examples to {traces_path}")
|
| 149 |
+
print(f"Artifacts stored under {artifact_root}")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if __name__ == "__main__":
|
| 153 |
+
main()
|
train_sft.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Supervised fine-tuning entrypoint for FlowOS."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args() -> argparse.Namespace:
|
| 15 |
+
parser = argparse.ArgumentParser(description="LoRA SFT training for FlowOS traces")
|
| 16 |
+
parser.add_argument("--dataset-path", default="outputs/sft_traces/traces.jsonl", help="JSONL trace file")
|
| 17 |
+
parser.add_argument("--model-id", default="Qwen/Qwen2.5-1.5B-Instruct", help="Base instruct model")
|
| 18 |
+
parser.add_argument("--output-dir", default="outputs/flowos-sft", help="Checkpoint output directory")
|
| 19 |
+
parser.add_argument("--learning-rate", type=float, default=2e-5, help="Learning rate")
|
| 20 |
+
parser.add_argument("--num-epochs", type=int, default=1, help="Training epochs")
|
| 21 |
+
parser.add_argument("--per-device-train-batch-size", type=int, default=1, help="Per-device batch size")
|
| 22 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=4, help="Gradient accumulation")
|
| 23 |
+
parser.add_argument("--logging-steps", type=int, default=1, help="Logging interval")
|
| 24 |
+
parser.add_argument("--save-steps", type=int, default=25, help="Checkpoint save interval")
|
| 25 |
+
parser.add_argument("--max-seq-length", type=int, default=2048, help="Sequence truncation length")
|
| 26 |
+
parser.add_argument("--lora-r", type=int, default=16, help="LoRA rank")
|
| 27 |
+
parser.add_argument("--lora-alpha", type=int, default=32, help="LoRA alpha")
|
| 28 |
+
parser.add_argument("--lora-dropout", type=float, default=0.05, help="LoRA dropout")
|
| 29 |
+
parser.add_argument("--report-to", default="none", choices=("none", "tensorboard", "wandb"), help="Logging backend")
|
| 30 |
+
return parser.parse_args()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def apply_chat_template(tokenizer: Any, messages: list[dict[str, str]], add_generation_prompt: bool) -> str:
|
| 34 |
+
try:
|
| 35 |
+
return tokenizer.apply_chat_template(
|
| 36 |
+
messages,
|
| 37 |
+
add_generation_prompt=add_generation_prompt,
|
| 38 |
+
tokenize=False,
|
| 39 |
+
enable_thinking=False,
|
| 40 |
+
)
|
| 41 |
+
except TypeError:
|
| 42 |
+
return tokenizer.apply_chat_template(
|
| 43 |
+
messages,
|
| 44 |
+
add_generation_prompt=add_generation_prompt,
|
| 45 |
+
tokenize=False,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def load_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 50 |
+
rows: list[dict[str, Any]] = []
|
| 51 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 52 |
+
for line in handle:
|
| 53 |
+
line = line.strip()
|
| 54 |
+
if not line:
|
| 55 |
+
continue
|
| 56 |
+
rows.append(json.loads(line))
|
| 57 |
+
return rows
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@dataclass
|
| 61 |
+
class FlowOSSFTDataset:
|
| 62 |
+
samples: list[dict[str, Any]]
|
| 63 |
+
tokenizer: Any
|
| 64 |
+
max_seq_length: int
|
| 65 |
+
|
| 66 |
+
def __len__(self) -> int:
|
| 67 |
+
return len(self.samples)
|
| 68 |
+
|
| 69 |
+
def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
|
| 70 |
+
sample = self.samples[idx]
|
| 71 |
+
prompt_text = apply_chat_template(
|
| 72 |
+
self.tokenizer,
|
| 73 |
+
[
|
| 74 |
+
{"role": "system", "content": sample["system_prompt"]},
|
| 75 |
+
{"role": "user", "content": sample["user_prompt"]},
|
| 76 |
+
],
|
| 77 |
+
add_generation_prompt=True,
|
| 78 |
+
)
|
| 79 |
+
full_text = prompt_text + sample["target_action"]
|
| 80 |
+
|
| 81 |
+
prompt_ids = self.tokenizer(
|
| 82 |
+
prompt_text,
|
| 83 |
+
truncation=True,
|
| 84 |
+
max_length=self.max_seq_length,
|
| 85 |
+
add_special_tokens=False,
|
| 86 |
+
)["input_ids"]
|
| 87 |
+
full_encoding = self.tokenizer(
|
| 88 |
+
full_text,
|
| 89 |
+
truncation=True,
|
| 90 |
+
max_length=self.max_seq_length,
|
| 91 |
+
add_special_tokens=False,
|
| 92 |
+
)
|
| 93 |
+
input_ids = full_encoding["input_ids"]
|
| 94 |
+
attention_mask = full_encoding["attention_mask"]
|
| 95 |
+
prompt_len = min(len(prompt_ids), len(input_ids))
|
| 96 |
+
labels = [-100] * prompt_len + input_ids[prompt_len:]
|
| 97 |
+
|
| 98 |
+
return {
|
| 99 |
+
"input_ids": torch.tensor(input_ids, dtype=torch.long),
|
| 100 |
+
"attention_mask": torch.tensor(attention_mask, dtype=torch.long),
|
| 101 |
+
"labels": torch.tensor(labels, dtype=torch.long),
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class SFTCollator:
|
| 106 |
+
def __init__(self, tokenizer: Any) -> None:
|
| 107 |
+
self.tokenizer = tokenizer
|
| 108 |
+
|
| 109 |
+
def __call__(self, features: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
|
| 110 |
+
pad_token_id = self.tokenizer.pad_token_id
|
| 111 |
+
max_len = max(feature["input_ids"].shape[0] for feature in features)
|
| 112 |
+
batch: dict[str, list[torch.Tensor]] = {"input_ids": [], "attention_mask": [], "labels": []}
|
| 113 |
+
for feature in features:
|
| 114 |
+
pad_len = max_len - feature["input_ids"].shape[0]
|
| 115 |
+
batch["input_ids"].append(
|
| 116 |
+
torch.cat([feature["input_ids"], torch.full((pad_len,), pad_token_id, dtype=torch.long)])
|
| 117 |
+
)
|
| 118 |
+
batch["attention_mask"].append(
|
| 119 |
+
torch.cat([feature["attention_mask"], torch.zeros(pad_len, dtype=torch.long)])
|
| 120 |
+
)
|
| 121 |
+
batch["labels"].append(
|
| 122 |
+
torch.cat([feature["labels"], torch.full((pad_len,), -100, dtype=torch.long)])
|
| 123 |
+
)
|
| 124 |
+
return {key: torch.stack(value) for key, value in batch.items()}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def main() -> None:
|
| 128 |
+
args = parse_args()
|
| 129 |
+
|
| 130 |
+
from peft import LoraConfig, get_peft_model
|
| 131 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 132 |
+
|
| 133 |
+
dataset_path = Path(args.dataset_path)
|
| 134 |
+
rows = load_jsonl(dataset_path)
|
| 135 |
+
if not rows:
|
| 136 |
+
raise SystemExit(f"No traces found at {dataset_path}")
|
| 137 |
+
|
| 138 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_id)
|
| 139 |
+
if tokenizer.pad_token is None:
|
| 140 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 141 |
+
|
| 142 |
+
model = AutoModelForCausalLM.from_pretrained(args.model_id)
|
| 143 |
+
model.config.use_cache = False
|
| 144 |
+
|
| 145 |
+
peft_config = LoraConfig(
|
| 146 |
+
r=args.lora_r,
|
| 147 |
+
lora_alpha=args.lora_alpha,
|
| 148 |
+
lora_dropout=args.lora_dropout,
|
| 149 |
+
bias="none",
|
| 150 |
+
task_type="CAUSAL_LM",
|
| 151 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 152 |
+
)
|
| 153 |
+
model = get_peft_model(model, peft_config)
|
| 154 |
+
|
| 155 |
+
train_dataset = FlowOSSFTDataset(rows, tokenizer, args.max_seq_length)
|
| 156 |
+
collator = SFTCollator(tokenizer)
|
| 157 |
+
|
| 158 |
+
training_args = TrainingArguments(
|
| 159 |
+
output_dir=args.output_dir,
|
| 160 |
+
learning_rate=args.learning_rate,
|
| 161 |
+
num_train_epochs=args.num_epochs,
|
| 162 |
+
per_device_train_batch_size=args.per_device_train_batch_size,
|
| 163 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 164 |
+
logging_steps=args.logging_steps,
|
| 165 |
+
save_steps=args.save_steps,
|
| 166 |
+
report_to=[] if args.report_to == "none" else [args.report_to],
|
| 167 |
+
remove_unused_columns=False,
|
| 168 |
+
bf16=torch.cuda.is_available(),
|
| 169 |
+
fp16=False,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
trainer = Trainer(
|
| 173 |
+
model=model,
|
| 174 |
+
args=training_args,
|
| 175 |
+
train_dataset=train_dataset,
|
| 176 |
+
data_collator=collator,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
trainer.train()
|
| 180 |
+
trainer.save_model(args.output_dir)
|
| 181 |
+
tokenizer.save_pretrained(args.output_dir)
|
| 182 |
+
print(f"Saved SFT model to {args.output_dir}")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
main()
|