Add sanitized teacher API inputs and generation scripts
Browse files- api_share_v1/data/semantic_location/teacher_inputs_rejected_3054.jsonl +0 -0
- api_share_v1/data/spatial_reasoning/spatial_teacher_inputs_10k.jsonl +0 -0
- api_share_v1/scripts/stage1/cot_sft_common.py +285 -0
- api_share_v1/train/stage1/sft/generate_spatial_teacher_cot.py +325 -0
- api_share_v1/train/stage1/sft/generate_teacher_cot.py +457 -0
- api_share_v1/train/stage1/sft/prompts/teacher_spatial_reasoning_v1.txt +30 -0
- api_share_v1/train/stage1/sft/prompts/teacher_structured_address_reasoning_v3.txt +16 -0
- api_share_v1/train/stage1/sft/schema.py +273 -0
api_share_v1/data/semantic_location/teacher_inputs_rejected_3054.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
api_share_v1/data/spatial_reasoning/spatial_teacher_inputs_10k.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
api_share_v1/scripts/stage1/cot_sft_common.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared I/O, validation, and OpenAI-compatible client helpers for CoT-SFT.
|
| 2 |
+
|
| 3 |
+
These helpers provide shared I/O and API plumbing. Legacy EGT teacher/judge
|
| 4 |
+
stages remain coordinate-blind. The independent-CoT scorer and judge use their
|
| 5 |
+
own explicit truth-audit boundary; target attachment still happens only during
|
| 6 |
+
final materialization.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import re
|
| 14 |
+
import time
|
| 15 |
+
import urllib.error
|
| 16 |
+
import urllib.request
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any, Iterator
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
STEP_RE = re.compile(r"^STEP\s+([1-3])\s*:\s*\S", flags=re.IGNORECASE)
|
| 22 |
+
COORDINATE_PAIR_RE = re.compile(
|
| 23 |
+
r"[-+]?\d{1,2}\.\d{4,}\s*[,;]\s*[-+]?\d{1,3}\.\d{4,}",
|
| 24 |
+
flags=re.IGNORECASE,
|
| 25 |
+
)
|
| 26 |
+
COORDINATE_VALUE_RE = re.compile(
|
| 27 |
+
r"\b(?:latitude|longitude|lat|lon)\b\s*(?:is|=|:|of)?\s*[-+]?\d{1,3}(?:\.\d+)?\b",
|
| 28 |
+
flags=re.IGNORECASE,
|
| 29 |
+
)
|
| 30 |
+
GEOHASH_VALUE_RE = re.compile(
|
| 31 |
+
r"\bgeohash\b\s*(?:is|=|:)?\s*['\"]?[0123456789bcdefghjkmnpqrstuvwxyz]{5,}\b",
|
| 32 |
+
flags=re.IGNORECASE,
|
| 33 |
+
)
|
| 34 |
+
HIDDEN_METADATA_RE = re.compile(r"\b(?:entity[_ ]?key|osm(?:[_ ]?(?:id|type))?|database id)\b", flags=re.IGNORECASE)
|
| 35 |
+
FENCE_RE = re.compile(r"^```(?:json)?\s*|\s*```$", flags=re.IGNORECASE)
|
| 36 |
+
COORDINATE_FIELD_NAMES = frozenset({"latitude", "longitude"})
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def clean_text(value: Any) -> str:
|
| 40 |
+
return "" if value is None else str(value).strip()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def contains_coordinate_field(value: Any) -> bool:
|
| 44 |
+
"""Return whether a nested payload exposes a coordinate schema key.
|
| 45 |
+
|
| 46 |
+
Text such as a POI named ``Latitude Restaurant`` is valid evidence and is
|
| 47 |
+
intentionally not interpreted as target-coordinate leakage.
|
| 48 |
+
"""
|
| 49 |
+
if isinstance(value, dict):
|
| 50 |
+
for key, nested_value in value.items():
|
| 51 |
+
if clean_text(key).casefold() in COORDINATE_FIELD_NAMES:
|
| 52 |
+
return True
|
| 53 |
+
if contains_coordinate_field(nested_value):
|
| 54 |
+
return True
|
| 55 |
+
elif isinstance(value, list):
|
| 56 |
+
return any(contains_coordinate_field(item) for item in value)
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def iter_jsonl(path: Path) -> Iterator[tuple[int, dict[str, Any]]]:
|
| 61 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 62 |
+
for row_number, line in enumerate(handle, start=1):
|
| 63 |
+
line = line.strip()
|
| 64 |
+
if not line:
|
| 65 |
+
continue
|
| 66 |
+
try:
|
| 67 |
+
row = json.loads(line)
|
| 68 |
+
except json.JSONDecodeError as exc:
|
| 69 |
+
raise ValueError(f"Invalid JSON at {path}:{row_number}") from exc
|
| 70 |
+
if not isinstance(row, dict):
|
| 71 |
+
raise ValueError(f"Expected a JSON object at {path}:{row_number}")
|
| 72 |
+
yield row_number, row
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_jsonl_by_sample_id(path: Path, *, allow_duplicate: bool = False) -> dict[str, dict[str, Any]]:
|
| 76 |
+
rows: dict[str, dict[str, Any]] = {}
|
| 77 |
+
for row_number, row in iter_jsonl(path):
|
| 78 |
+
sample_id = clean_text(row.get("sample_id"))
|
| 79 |
+
if not sample_id:
|
| 80 |
+
raise ValueError(f"Missing sample_id at {path}:{row_number}")
|
| 81 |
+
if sample_id in rows and not allow_duplicate:
|
| 82 |
+
raise ValueError(f"Duplicate sample_id at {path}:{row_number}: {sample_id}")
|
| 83 |
+
rows[sample_id] = row
|
| 84 |
+
return rows
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def parse_json_object(text: str) -> tuple[dict[str, Any] | None, str | None]:
|
| 88 |
+
"""Accept a strict JSON object or one markdown-fenced/object-containing reply."""
|
| 89 |
+
text = clean_text(text)
|
| 90 |
+
if not text:
|
| 91 |
+
return None, "empty_response"
|
| 92 |
+
unfenced = FENCE_RE.sub("", text).strip()
|
| 93 |
+
candidates = [unfenced]
|
| 94 |
+
first = unfenced.find("{")
|
| 95 |
+
last = unfenced.rfind("}")
|
| 96 |
+
if first >= 0 and last > first:
|
| 97 |
+
candidates.append(unfenced[first : last + 1])
|
| 98 |
+
for candidate in candidates:
|
| 99 |
+
try:
|
| 100 |
+
parsed = json.loads(candidate)
|
| 101 |
+
except json.JSONDecodeError:
|
| 102 |
+
continue
|
| 103 |
+
if isinstance(parsed, dict):
|
| 104 |
+
return parsed, None
|
| 105 |
+
return None, "response_is_not_object"
|
| 106 |
+
return None, "invalid_json"
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def query_specific_literals(query: str, visible_evidence: dict[str, Any] | None) -> list[str]:
|
| 110 |
+
values: list[str] = []
|
| 111 |
+
if visible_evidence:
|
| 112 |
+
for key in ("country", "feature_type", "english_name", "feature_category"):
|
| 113 |
+
value = clean_text(visible_evidence.get(key))
|
| 114 |
+
if len(value) >= 3:
|
| 115 |
+
values.append(value.casefold())
|
| 116 |
+
for match in re.finditer(r'"([^"\n]{3,})"', query):
|
| 117 |
+
values.append(match.group(1).strip().casefold())
|
| 118 |
+
return list(dict.fromkeys(values))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def validate_reasoning(
|
| 122 |
+
payload: dict[str, Any] | None,
|
| 123 |
+
*,
|
| 124 |
+
query: str,
|
| 125 |
+
visible_evidence: dict[str, Any] | None,
|
| 126 |
+
minimum_steps: int = 2,
|
| 127 |
+
maximum_steps: int = 3,
|
| 128 |
+
) -> tuple[list[str] | None, list[str]]:
|
| 129 |
+
"""Validate the deliberately narrow rationale format before it reaches SFT."""
|
| 130 |
+
if not isinstance(payload, dict):
|
| 131 |
+
return None, ["invalid_json_object"]
|
| 132 |
+
if set(payload) != {"reasoning"}:
|
| 133 |
+
return None, ["unexpected_output_fields"]
|
| 134 |
+
reasoning = payload.get("reasoning")
|
| 135 |
+
if not isinstance(reasoning, list):
|
| 136 |
+
return None, ["reasoning_not_list"]
|
| 137 |
+
if not minimum_steps <= len(reasoning) <= maximum_steps:
|
| 138 |
+
return None, ["invalid_step_count"]
|
| 139 |
+
|
| 140 |
+
normalized_steps: list[str] = []
|
| 141 |
+
errors: list[str] = []
|
| 142 |
+
for index, raw_step in enumerate(reasoning, start=1):
|
| 143 |
+
step = clean_text(raw_step)
|
| 144 |
+
if not isinstance(raw_step, str):
|
| 145 |
+
errors.append("non_string_step")
|
| 146 |
+
continue
|
| 147 |
+
if not 12 <= len(step) <= 360:
|
| 148 |
+
errors.append("invalid_step_length")
|
| 149 |
+
prefix = STEP_RE.match(step)
|
| 150 |
+
if prefix is None or int(prefix.group(1)) != index:
|
| 151 |
+
errors.append("invalid_step_prefix")
|
| 152 |
+
normalized_steps.append(step)
|
| 153 |
+
combined = "\n".join(normalized_steps)
|
| 154 |
+
# A rationale may correctly state that it does not infer a coordinate. Only
|
| 155 |
+
# an actual numeric coordinate/geohash value constitutes target leakage.
|
| 156 |
+
if COORDINATE_PAIR_RE.search(combined) or COORDINATE_VALUE_RE.search(combined) or GEOHASH_VALUE_RE.search(combined):
|
| 157 |
+
errors.append("coordinate_leakage")
|
| 158 |
+
if HIDDEN_METADATA_RE.search(combined):
|
| 159 |
+
errors.append("hidden_metadata_reference")
|
| 160 |
+
if len(set(step.casefold() for step in normalized_steps)) != len(normalized_steps):
|
| 161 |
+
errors.append("duplicate_reasoning_step")
|
| 162 |
+
|
| 163 |
+
literals = query_specific_literals(query, visible_evidence)
|
| 164 |
+
lowered = combined.casefold()
|
| 165 |
+
if literals and not any(literal in lowered for literal in literals):
|
| 166 |
+
errors.append("no_visible_evidence_reference")
|
| 167 |
+
return (normalized_steps if not errors else None), sorted(set(errors))
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def response_content(message: dict[str, Any]) -> str:
|
| 171 |
+
content = message.get("content")
|
| 172 |
+
if isinstance(content, str):
|
| 173 |
+
return content
|
| 174 |
+
if isinstance(content, list):
|
| 175 |
+
fragments: list[str] = []
|
| 176 |
+
for item in content:
|
| 177 |
+
if isinstance(item, dict) and isinstance(item.get("text"), str):
|
| 178 |
+
fragments.append(item["text"])
|
| 179 |
+
elif isinstance(item, str):
|
| 180 |
+
fragments.append(item)
|
| 181 |
+
return "".join(fragments)
|
| 182 |
+
return ""
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def call_chat_completion(
|
| 186 |
+
*,
|
| 187 |
+
base_url: str,
|
| 188 |
+
model: str,
|
| 189 |
+
api_key: str,
|
| 190 |
+
messages: list[dict[str, str]],
|
| 191 |
+
temperature: float,
|
| 192 |
+
max_tokens: int,
|
| 193 |
+
timeout_seconds: float,
|
| 194 |
+
json_mode: bool,
|
| 195 |
+
native_thinking: str | None = None,
|
| 196 |
+
reasoning_mode: str | None = None,
|
| 197 |
+
extra_headers: dict[str, str] | None = None,
|
| 198 |
+
) -> tuple[str, dict[str, Any]]:
|
| 199 |
+
payload: dict[str, Any] = {
|
| 200 |
+
"model": model,
|
| 201 |
+
"messages": messages,
|
| 202 |
+
"temperature": temperature,
|
| 203 |
+
"max_tokens": max_tokens,
|
| 204 |
+
"stream": False,
|
| 205 |
+
}
|
| 206 |
+
if json_mode:
|
| 207 |
+
payload["response_format"] = {"type": "json_object"}
|
| 208 |
+
if native_thinking in {"on", "off"}:
|
| 209 |
+
payload["chat_template_kwargs"] = {"enable_thinking": native_thinking == "on"}
|
| 210 |
+
if reasoning_mode in {"on", "off"}:
|
| 211 |
+
# OpenRouter-compatible providers use this field to control hidden
|
| 212 |
+
# reasoning. It is separate from local vLLM chat-template thinking.
|
| 213 |
+
payload["reasoning"] = {"enabled": reasoning_mode == "on"}
|
| 214 |
+
|
| 215 |
+
headers = {
|
| 216 |
+
"Authorization": f"Bearer {api_key}",
|
| 217 |
+
"Content-Type": "application/json",
|
| 218 |
+
}
|
| 219 |
+
if extra_headers:
|
| 220 |
+
headers.update(extra_headers)
|
| 221 |
+
request = urllib.request.Request(
|
| 222 |
+
f"{base_url.rstrip('/')}/chat/completions",
|
| 223 |
+
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
|
| 224 |
+
headers=headers,
|
| 225 |
+
method="POST",
|
| 226 |
+
)
|
| 227 |
+
started_at = time.perf_counter()
|
| 228 |
+
try:
|
| 229 |
+
with urllib.request.urlopen(request, timeout=timeout_seconds) as response: # noqa: S310 - caller chooses endpoint
|
| 230 |
+
raw_response = response.read().decode("utf-8")
|
| 231 |
+
except urllib.error.HTTPError as exc:
|
| 232 |
+
body = exc.read().decode("utf-8", errors="replace")
|
| 233 |
+
raise RuntimeError(f"HTTP {exc.code}: {body[:1000]}") from exc
|
| 234 |
+
except urllib.error.URLError as exc:
|
| 235 |
+
raise RuntimeError(f"Connection failed: {exc}") from exc
|
| 236 |
+
try:
|
| 237 |
+
response = json.loads(raw_response)
|
| 238 |
+
except json.JSONDecodeError as exc:
|
| 239 |
+
raise RuntimeError(f"Endpoint returned invalid JSON: {raw_response[:1000]}") from exc
|
| 240 |
+
choices = response.get("choices") or []
|
| 241 |
+
if not choices:
|
| 242 |
+
raise RuntimeError(f"Endpoint returned no choices: {raw_response[:1000]}")
|
| 243 |
+
message = choices[0].get("message") or {}
|
| 244 |
+
content = response_content(message)
|
| 245 |
+
if not content:
|
| 246 |
+
raise RuntimeError(f"Endpoint returned empty assistant content: {raw_response[:1000]}")
|
| 247 |
+
metadata = {
|
| 248 |
+
"returned_model": response.get("model") or model,
|
| 249 |
+
"finish_reason": choices[0].get("finish_reason"),
|
| 250 |
+
"usage": response.get("usage"),
|
| 251 |
+
"latency_seconds": round(time.perf_counter() - started_at, 4),
|
| 252 |
+
}
|
| 253 |
+
return content, metadata
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def call_with_retries(
|
| 257 |
+
*,
|
| 258 |
+
attempts: int,
|
| 259 |
+
request: Any,
|
| 260 |
+
) -> tuple[str, dict[str, Any], int]:
|
| 261 |
+
if attempts < 1:
|
| 262 |
+
raise ValueError("attempts must be at least 1")
|
| 263 |
+
last_error: Exception | None = None
|
| 264 |
+
for attempt in range(1, attempts + 1):
|
| 265 |
+
try:
|
| 266 |
+
content, metadata = request()
|
| 267 |
+
return content, metadata, attempt
|
| 268 |
+
except Exception as exc: # noqa: BLE001 - preserve endpoint details in the audit row
|
| 269 |
+
last_error = exc
|
| 270 |
+
if attempt < attempts:
|
| 271 |
+
time.sleep(min(8.0, 0.5 * (2 ** (attempt - 1))))
|
| 272 |
+
raise RuntimeError(str(last_error))
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def api_key_from_env(name: str, *, default: str | None = None) -> str:
|
| 276 |
+
value = os.environ.get(name)
|
| 277 |
+
if value:
|
| 278 |
+
return value
|
| 279 |
+
if default is not None:
|
| 280 |
+
return default
|
| 281 |
+
raise ValueError(f"Environment variable {name} is required")
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def safe_error_text(exc: Exception) -> str:
|
| 285 |
+
return clean_text(str(exc))[:2000]
|
api_share_v1/train/stage1/sft/generate_spatial_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|
| 3 |
+
|
| 4 |
+
The input contains only model-visible synthetic requests. The local spatial
|
| 5 |
+
builder owns the mathematical reference endpoint; this script asks a teacher
|
| 6 |
+
API for an independent reasoning trace and an audit-only endpoint estimate.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
import re
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Iterable
|
| 20 |
+
|
| 21 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[3]
|
| 22 |
+
if str(PROJECT_ROOT) not in sys.path:
|
| 23 |
+
sys.path.insert(0, str(PROJECT_ROOT))
|
| 24 |
+
|
| 25 |
+
from scripts.stage1.cot_sft_common import ( # noqa: E402
|
| 26 |
+
api_key_from_env,
|
| 27 |
+
call_chat_completion,
|
| 28 |
+
call_with_retries,
|
| 29 |
+
clean_text,
|
| 30 |
+
iter_jsonl,
|
| 31 |
+
load_jsonl_by_sample_id,
|
| 32 |
+
parse_json_object,
|
| 33 |
+
safe_error_text,
|
| 34 |
+
)
|
| 35 |
+
from train.stage1.sft.generate_teacher_cot import ( # noqa: E402
|
| 36 |
+
call_openai_sdk_chat_completion,
|
| 37 |
+
)
|
| 38 |
+
from train.stage1.sft.schema import ( # noqa: E402
|
| 39 |
+
load_system_prompt,
|
| 40 |
+
validate_query,
|
| 41 |
+
validate_reasoning,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
GENERATOR_VERSION = "stage1-semantic-spatial-teacher-cot-api-v1"
|
| 46 |
+
TEACHER_PROMPT_VERSION = "semantic-spatial-teacher-spherical-v1"
|
| 47 |
+
TEACHER_PROMPT_PATH = Path(__file__).with_name("prompts") / "teacher_spatial_reasoning_v1.txt"
|
| 48 |
+
DEFAULT_INPUT = Path("data/stage1/semantic_spatial_reasoning_sft_v1/spatial_teacher_inputs_v1.jsonl")
|
| 49 |
+
DEFAULT_OUTPUT = Path("data/stage1/semantic_spatial_reasoning_sft_v1/spatial_teacher_cot_v1.jsonl")
|
| 50 |
+
|
| 51 |
+
_COORDINATE_TEXT_RE = re.compile(
|
| 52 |
+
r"(?:\b(?:lat(?:itude)?|lon(?:gitude)?|lng)\s*[:=]\s*[+-]?\d|"
|
| 53 |
+
r"[+-]?\d{1,2}(?:\.\d+)?\s*\u00b0?\s*[NS]\b|"
|
| 54 |
+
r"[+-]?\d{1,3}(?:\.\d+)?\s*\u00b0?\s*[EW]\b|"
|
| 55 |
+
r"(?<![\w.])[+-]?\d{1,2}\.\d{3,}\s*[,;/]\s*"
|
| 56 |
+
r"[+-]?\d{1,3}\.\d{3,}(?![\w.]))",
|
| 57 |
+
flags=re.IGNORECASE,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def teacher_messages(query: str, system_prompt: str) -> list[dict[str, str]]:
|
| 62 |
+
"""Build the only messages sent to the spatial teacher endpoint."""
|
| 63 |
+
|
| 64 |
+
return [
|
| 65 |
+
{"role": "system", "content": system_prompt},
|
| 66 |
+
{"role": "user", "content": validate_query(query)},
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def validate_input_row(row: dict[str, Any], *, row_number: int, path: Path) -> tuple[str, str]:
|
| 71 |
+
if set(row) != {"sample_id", "query"}:
|
| 72 |
+
raise ValueError(
|
| 73 |
+
f"spatial teacher input at {path}:{row_number} must contain exactly sample_id and query"
|
| 74 |
+
)
|
| 75 |
+
sample_id = clean_text(row.get("sample_id"))
|
| 76 |
+
if not sample_id:
|
| 77 |
+
raise ValueError(f"missing sample_id at {path}:{row_number}")
|
| 78 |
+
try:
|
| 79 |
+
query = validate_query(row.get("query"))
|
| 80 |
+
except ValueError as exc:
|
| 81 |
+
raise ValueError(f"invalid query at {path}:{row_number}: {exc}") from exc
|
| 82 |
+
return sample_id, query
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _validate_coordinates(value: Any, *, field_name: str) -> tuple[float, float]:
|
| 86 |
+
if not isinstance(value, dict) or set(value) != {"latitude", "longitude"}:
|
| 87 |
+
raise ValueError(f"{field_name} must contain exactly latitude and longitude")
|
| 88 |
+
latitude = value.get("latitude")
|
| 89 |
+
longitude = value.get("longitude")
|
| 90 |
+
if (
|
| 91 |
+
isinstance(latitude, bool)
|
| 92 |
+
or isinstance(longitude, bool)
|
| 93 |
+
or not isinstance(latitude, (int, float))
|
| 94 |
+
or not isinstance(longitude, (int, float))
|
| 95 |
+
):
|
| 96 |
+
raise ValueError(f"{field_name} latitude and longitude must be JSON numbers")
|
| 97 |
+
lat = float(latitude)
|
| 98 |
+
lon = float(longitude)
|
| 99 |
+
if not math.isfinite(lat) or not -90.0 <= lat <= 90.0:
|
| 100 |
+
raise ValueError(f"{field_name} latitude is outside [-90, 90]")
|
| 101 |
+
if not math.isfinite(lon) or not -180.0 <= lon <= 180.0:
|
| 102 |
+
raise ValueError(f"{field_name} longitude is outside [-180, 180]")
|
| 103 |
+
return lat, lon
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def validate_spatial_teacher_payload(payload: Any) -> tuple[dict[str, Any] | None, list[str]]:
|
| 107 |
+
"""Validate the spatial teacher contract without trusting its estimate."""
|
| 108 |
+
|
| 109 |
+
if not isinstance(payload, dict):
|
| 110 |
+
return None, ["invalid_json_object"]
|
| 111 |
+
if set(payload) != {"reasoning", "audit_coordinates"}:
|
| 112 |
+
return None, ["unexpected_output_fields"]
|
| 113 |
+
try:
|
| 114 |
+
reasoning = validate_reasoning(payload.get("reasoning"))
|
| 115 |
+
teacher_latitude, teacher_longitude = _validate_coordinates(
|
| 116 |
+
payload.get("audit_coordinates"), field_name="audit_coordinates"
|
| 117 |
+
)
|
| 118 |
+
except ValueError as exc:
|
| 119 |
+
return None, [str(exc)]
|
| 120 |
+
if any(_COORDINATE_TEXT_RE.search(step) for step in reasoning):
|
| 121 |
+
return None, ["destination or intermediate coordinates must not appear in reasoning"]
|
| 122 |
+
return {
|
| 123 |
+
"reasoning": reasoning,
|
| 124 |
+
"teacher_audit_latitude": teacher_latitude,
|
| 125 |
+
"teacher_audit_longitude": teacher_longitude,
|
| 126 |
+
}, []
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def build_result(
|
| 130 |
+
row: dict[str, Any],
|
| 131 |
+
args: argparse.Namespace,
|
| 132 |
+
*,
|
| 133 |
+
api_key: str,
|
| 134 |
+
system_prompt: str,
|
| 135 |
+
) -> dict[str, Any]:
|
| 136 |
+
sample_id = clean_text(row["sample_id"])
|
| 137 |
+
query = clean_text(row["query"])
|
| 138 |
+
messages = teacher_messages(query, system_prompt)
|
| 139 |
+
if args.transport == "openai":
|
| 140 |
+
request = lambda: call_openai_sdk_chat_completion(
|
| 141 |
+
base_url=args.base_url,
|
| 142 |
+
model=args.model,
|
| 143 |
+
api_key=api_key,
|
| 144 |
+
messages=messages,
|
| 145 |
+
temperature=args.temperature,
|
| 146 |
+
max_tokens=args.max_tokens,
|
| 147 |
+
timeout_seconds=args.timeout_seconds,
|
| 148 |
+
json_mode=args.json_mode,
|
| 149 |
+
native_thinking=args.native_thinking,
|
| 150 |
+
reasoning_mode=args.reasoning_mode,
|
| 151 |
+
)
|
| 152 |
+
else:
|
| 153 |
+
request = lambda: call_chat_completion(
|
| 154 |
+
base_url=args.base_url,
|
| 155 |
+
model=args.model,
|
| 156 |
+
api_key=api_key,
|
| 157 |
+
messages=messages,
|
| 158 |
+
temperature=args.temperature,
|
| 159 |
+
max_tokens=args.max_tokens,
|
| 160 |
+
timeout_seconds=args.timeout_seconds,
|
| 161 |
+
json_mode=args.json_mode,
|
| 162 |
+
native_thinking=(args.native_thinking if args.native_thinking != "omit" else None),
|
| 163 |
+
reasoning_mode=(args.reasoning_mode if args.reasoning_mode != "omit" else None),
|
| 164 |
+
extra_headers={"User-Agent": "GeoCoding-Spatial-Teacher-CoT/1.0"},
|
| 165 |
+
)
|
| 166 |
+
common = {
|
| 167 |
+
"sample_id": sample_id,
|
| 168 |
+
"generator_version": GENERATOR_VERSION,
|
| 169 |
+
"model": args.model,
|
| 170 |
+
"base_url": args.base_url.rstrip("/"),
|
| 171 |
+
"prompt_version": TEACHER_PROMPT_VERSION,
|
| 172 |
+
"native_thinking": args.native_thinking,
|
| 173 |
+
"reasoning_mode": args.reasoning_mode,
|
| 174 |
+
"transport": args.transport,
|
| 175 |
+
}
|
| 176 |
+
try:
|
| 177 |
+
raw_response, metadata, attempts = call_with_retries(
|
| 178 |
+
attempts=args.max_attempts,
|
| 179 |
+
request=request,
|
| 180 |
+
)
|
| 181 |
+
except Exception as exc: # noqa: BLE001 - preserve one auditable failure row
|
| 182 |
+
return {**common, "status": "request_error", "error": safe_error_text(exc)}
|
| 183 |
+
|
| 184 |
+
payload, parse_error = parse_json_object(raw_response)
|
| 185 |
+
if parse_error:
|
| 186 |
+
return {
|
| 187 |
+
**common,
|
| 188 |
+
"status": "invalid_generation",
|
| 189 |
+
"raw_response": raw_response,
|
| 190 |
+
"validation_errors": [parse_error],
|
| 191 |
+
"request_attempts": attempts,
|
| 192 |
+
**metadata,
|
| 193 |
+
}
|
| 194 |
+
validated, validation_errors = validate_spatial_teacher_payload(payload)
|
| 195 |
+
if validation_errors or validated is None:
|
| 196 |
+
return {
|
| 197 |
+
**common,
|
| 198 |
+
"status": "invalid_generation",
|
| 199 |
+
"raw_response": raw_response,
|
| 200 |
+
"validation_errors": validation_errors,
|
| 201 |
+
"request_attempts": attempts,
|
| 202 |
+
**metadata,
|
| 203 |
+
}
|
| 204 |
+
return {
|
| 205 |
+
**common,
|
| 206 |
+
"status": "generated",
|
| 207 |
+
"reasoning": validated["reasoning"],
|
| 208 |
+
"teacher_audit_latitude": validated["teacher_audit_latitude"],
|
| 209 |
+
"teacher_audit_longitude": validated["teacher_audit_longitude"],
|
| 210 |
+
"raw_response": raw_response,
|
| 211 |
+
"request_attempts": attempts,
|
| 212 |
+
**metadata,
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def parse_args(argv: Iterable[str] | None = None) -> argparse.Namespace:
|
| 217 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 218 |
+
parser.add_argument("--input", type=Path, default=DEFAULT_INPUT)
|
| 219 |
+
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
|
| 220 |
+
parser.add_argument("--prompt", type=Path, default=TEACHER_PROMPT_PATH)
|
| 221 |
+
parser.add_argument("--base-url", default="http://127.0.0.1:8000/v1")
|
| 222 |
+
parser.add_argument("--model", required=True)
|
| 223 |
+
parser.add_argument("--api-key-env", default="LOCAL_OPENAI_API_KEY")
|
| 224 |
+
parser.add_argument("--transport", choices=("openai", "urllib"), default="openai")
|
| 225 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 226 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
| 227 |
+
parser.add_argument("--max-tokens", type=int, default=1024)
|
| 228 |
+
parser.add_argument("--timeout-seconds", type=float, default=300.0)
|
| 229 |
+
parser.add_argument("--max-attempts", type=int, default=3)
|
| 230 |
+
parser.add_argument("--native-thinking", choices=("omit", "off", "on"), default="omit")
|
| 231 |
+
parser.add_argument("--reasoning-mode", choices=("omit", "off", "on"), default="omit")
|
| 232 |
+
parser.add_argument("--json-mode", action=argparse.BooleanOptionalAction, default=True)
|
| 233 |
+
parser.add_argument("--resume", action=argparse.BooleanOptionalAction, default=True)
|
| 234 |
+
parser.add_argument("--retry-non-generated", action="store_true")
|
| 235 |
+
parser.add_argument("--allow-mixed-models", action="store_true")
|
| 236 |
+
parser.add_argument("--overwrite", action="store_true")
|
| 237 |
+
parser.add_argument("--limit", type=int)
|
| 238 |
+
parser.add_argument("--progress-every", type=int, default=100)
|
| 239 |
+
parser.add_argument("--validate-only", action="store_true")
|
| 240 |
+
return parser.parse_args(list(argv) if argv is not None else None)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def main(argv: Iterable[str] | None = None) -> int:
|
| 244 |
+
args = parse_args(argv)
|
| 245 |
+
if args.workers < 1 or args.max_attempts < 1:
|
| 246 |
+
raise ValueError("workers and max-attempts must be at least 1")
|
| 247 |
+
if args.limit is not None and args.limit < 0:
|
| 248 |
+
raise ValueError("limit must be non-negative")
|
| 249 |
+
if args.overwrite and args.resume:
|
| 250 |
+
args.resume = False
|
| 251 |
+
if args.allow_mixed_models and not (args.resume and args.retry_non_generated):
|
| 252 |
+
raise ValueError("--allow-mixed-models requires --resume and --retry-non-generated")
|
| 253 |
+
if args.output.exists() and not args.resume and not args.overwrite:
|
| 254 |
+
raise FileExistsError(f"output exists; use --resume or --overwrite: {args.output}")
|
| 255 |
+
|
| 256 |
+
system_prompt = load_system_prompt(args.prompt)
|
| 257 |
+
existing = (
|
| 258 |
+
load_jsonl_by_sample_id(args.output, allow_duplicate=True)
|
| 259 |
+
if args.resume and args.output.exists()
|
| 260 |
+
else {}
|
| 261 |
+
)
|
| 262 |
+
for sample_id, result in existing.items():
|
| 263 |
+
if (
|
| 264 |
+
clean_text(result.get("model"))
|
| 265 |
+
and result.get("model") != args.model
|
| 266 |
+
and not args.allow_mixed_models
|
| 267 |
+
):
|
| 268 |
+
raise ValueError(f"resume model mismatch for {sample_id}")
|
| 269 |
+
if clean_text(result.get("prompt_version")) and result.get("prompt_version") != TEACHER_PROMPT_VERSION:
|
| 270 |
+
raise ValueError(f"resume prompt mismatch for {sample_id}")
|
| 271 |
+
if clean_text(result.get("base_url")) and result.get("base_url") != args.base_url.rstrip("/"):
|
| 272 |
+
raise ValueError(f"resume base URL mismatch for {sample_id}")
|
| 273 |
+
|
| 274 |
+
completed = {
|
| 275 |
+
sample_id
|
| 276 |
+
for sample_id, result in existing.items()
|
| 277 |
+
if not args.retry_non_generated or clean_text(result.get("status")) == "generated"
|
| 278 |
+
}
|
| 279 |
+
pending: list[dict[str, str]] = []
|
| 280 |
+
seen: set[str] = set()
|
| 281 |
+
total = 0
|
| 282 |
+
for row_number, row in iter_jsonl(args.input):
|
| 283 |
+
sample_id, query = validate_input_row(row, row_number=row_number, path=args.input)
|
| 284 |
+
if sample_id in seen:
|
| 285 |
+
raise ValueError(f"duplicate sample_id in input: {sample_id}")
|
| 286 |
+
seen.add(sample_id)
|
| 287 |
+
total += 1
|
| 288 |
+
if sample_id not in completed:
|
| 289 |
+
pending.append({"sample_id": sample_id, "query": query})
|
| 290 |
+
if args.limit is not None:
|
| 291 |
+
pending = pending[: args.limit]
|
| 292 |
+
if args.validate_only:
|
| 293 |
+
print(f"Spatial teacher input validation complete: total={total} pending={len(pending)}")
|
| 294 |
+
return 0
|
| 295 |
+
|
| 296 |
+
api_key = api_key_from_env(args.api_key_env, default="EMPTY")
|
| 297 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 298 |
+
mode = "a" if args.resume and args.output.exists() else "w"
|
| 299 |
+
counts: dict[str, int] = {}
|
| 300 |
+
with args.output.open(mode, encoding="utf-8", newline="") as handle:
|
| 301 |
+
with ThreadPoolExecutor(max_workers=args.workers) as executor:
|
| 302 |
+
futures = [
|
| 303 |
+
executor.submit(build_result, row, args, api_key=api_key, system_prompt=system_prompt)
|
| 304 |
+
for row in pending
|
| 305 |
+
]
|
| 306 |
+
for index, future in enumerate(as_completed(futures), start=1):
|
| 307 |
+
result = future.result()
|
| 308 |
+
status = clean_text(result.get("status")) or "missing_status"
|
| 309 |
+
counts[status] = counts.get(status, 0) + 1
|
| 310 |
+
handle.write(json.dumps(result, ensure_ascii=False, separators=(",", ":")) + "\n")
|
| 311 |
+
handle.flush()
|
| 312 |
+
if args.progress_every > 0 and (index % args.progress_every == 0 or index == len(pending)):
|
| 313 |
+
print(
|
| 314 |
+
f"generated={index}/{len(pending)} statuses={json.dumps(counts, sort_keys=True)}",
|
| 315 |
+
flush=True,
|
| 316 |
+
)
|
| 317 |
+
print(
|
| 318 |
+
f"Spatial teacher CoT generation complete: output={args.output} "
|
| 319 |
+
f"statuses={json.dum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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate query-only semantic-location CoT with an OpenAI-compatible teacher API.
|
| 3 |
+
|
| 4 |
+
The generated artifact is an audit file. Rows that pass deterministic format
|
| 5 |
+
and leakage checks are marked ``generated`` rather than ``accepted``; a later
|
| 6 |
+
review or judge must promote reasoning before the final SFT materializer uses
|
| 7 |
+
it as verified reasoning. Frozen targets, manifests, and Wikidata evidence are
|
| 8 |
+
never loaded or sent to the teacher.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
import re
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, Iterable
|
| 22 |
+
|
| 23 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[3]
|
| 24 |
+
if str(PROJECT_ROOT) not in sys.path:
|
| 25 |
+
sys.path.insert(0, str(PROJECT_ROOT))
|
| 26 |
+
|
| 27 |
+
from scripts.stage1.cot_sft_common import ( # noqa: E402
|
| 28 |
+
api_key_from_env,
|
| 29 |
+
call_chat_completion,
|
| 30 |
+
call_with_retries,
|
| 31 |
+
clean_text,
|
| 32 |
+
iter_jsonl,
|
| 33 |
+
load_jsonl_by_sample_id,
|
| 34 |
+
parse_json_object,
|
| 35 |
+
safe_error_text,
|
| 36 |
+
)
|
| 37 |
+
from train.stage1.sft.schema import ( # noqa: E402
|
| 38 |
+
load_system_prompt,
|
| 39 |
+
validate_query,
|
| 40 |
+
validate_reasoning,
|
| 41 |
+
validate_resolved_location,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
GENERATOR_VERSION = "stage1-semantic-location-teacher-cot-api-v4"
|
| 46 |
+
TEACHER_PROMPT_VERSION = "semantic-location-teacher-structured-address-gps-audit-v3"
|
| 47 |
+
TEACHER_PROMPT_PATH = (
|
| 48 |
+
Path(__file__).with_name("prompts") / "teacher_structured_address_reasoning_v3.txt"
|
| 49 |
+
)
|
| 50 |
+
DEFAULT_INPUT = Path(
|
| 51 |
+
"data/stage1/semantic_location_reasoning_sft_v1/"
|
| 52 |
+
"pending_wikidata_5k_v3/teacher_inputs_pilot_140_v2.jsonl"
|
| 53 |
+
)
|
| 54 |
+
DEFAULT_OUTPUT = Path(
|
| 55 |
+
"data/stage1/semantic_location_reasoning_sft_v1/"
|
| 56 |
+
"pending_wikidata_5k_v3/teacher_cot_pilot_140_v4.jsonl"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
_COORDINATE_TEXT_RE = re.compile(
|
| 60 |
+
r"(?:\b(?:lat(?:itude)?|lon(?:gitude)?|lng)\s*[:=]\s*[+-]?\d|"
|
| 61 |
+
r"[+-]?\d{1,2}(?:\.\d+)?\s*\u00b0?\s*[NS]\b|"
|
| 62 |
+
r"[+-]?\d{1,3}(?:\.\d+)?\s*\u00b0?\s*[EW]\b|"
|
| 63 |
+
r"(?<![\w.])[+-]?\d{1,2}\.\d{3,}\s*[,;/]\s*"
|
| 64 |
+
r"[+-]?\d{1,3}\.\d{3,}(?![\w.]))",
|
| 65 |
+
flags=re.IGNORECASE,
|
| 66 |
+
)
|
| 67 |
+
_UNRESOLVED_LOCATIONS = frozenset(
|
| 68 |
+
{"unresolved", "ambiguous", "unknown", "insufficient information"}
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def teacher_messages(query: str, system_prompt: str) -> list[dict[str, str]]:
|
| 73 |
+
"""Build the only messages sent to the teacher endpoint."""
|
| 74 |
+
|
| 75 |
+
return [
|
| 76 |
+
{"role": "system", "content": system_prompt},
|
| 77 |
+
{"role": "user", "content": validate_query(query)},
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def validate_input_row(row: dict[str, Any], *, row_number: int, path: Path) -> tuple[str, str]:
|
| 82 |
+
if set(row) != {"sample_id", "query"}:
|
| 83 |
+
raise ValueError(
|
| 84 |
+
f"teacher input at {path}:{row_number} must contain exactly sample_id and query"
|
| 85 |
+
)
|
| 86 |
+
sample_id = clean_text(row.get("sample_id"))
|
| 87 |
+
if not sample_id:
|
| 88 |
+
raise ValueError(f"missing sample_id at {path}:{row_number}")
|
| 89 |
+
try:
|
| 90 |
+
query = validate_query(row.get("query"))
|
| 91 |
+
except ValueError as exc:
|
| 92 |
+
raise ValueError(f"invalid query at {path}:{row_number}: {exc}") from exc
|
| 93 |
+
return sample_id, query
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _validate_audit_coordinates(value: Any) -> tuple[float, float]:
|
| 97 |
+
if not isinstance(value, dict) or set(value) != {"latitude", "longitude"}:
|
| 98 |
+
raise ValueError("audit_coordinates must contain exactly latitude and longitude")
|
| 99 |
+
latitude = value.get("latitude")
|
| 100 |
+
longitude = value.get("longitude")
|
| 101 |
+
if (
|
| 102 |
+
isinstance(latitude, bool)
|
| 103 |
+
or isinstance(longitude, bool)
|
| 104 |
+
or not isinstance(latitude, (int, float))
|
| 105 |
+
or not isinstance(longitude, (int, float))
|
| 106 |
+
):
|
| 107 |
+
raise ValueError("audit_coordinates latitude and longitude must be JSON numbers")
|
| 108 |
+
lat = float(latitude)
|
| 109 |
+
lon = float(longitude)
|
| 110 |
+
if not math.isfinite(lat) or not -90.0 <= lat <= 90.0:
|
| 111 |
+
raise ValueError("audit latitude is outside [-90, 90]")
|
| 112 |
+
if not math.isfinite(lon) or not -180.0 <= lon <= 180.0:
|
| 113 |
+
raise ValueError("audit longitude is outside [-180, 180]")
|
| 114 |
+
return lat, lon
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _validate_structured_address_shape(resolved_location: str) -> None:
|
| 118 |
+
if resolved_location.casefold() in _UNRESOLVED_LOCATIONS:
|
| 119 |
+
return
|
| 120 |
+
components = [component.strip() for component in resolved_location.split(",")]
|
| 121 |
+
if len(components) < 4 or any(not component for component in components):
|
| 122 |
+
raise ValueError(
|
| 123 |
+
"resolved_location must contain at least country, locality, street, and named feature"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def validate_teacher_payload(payload: Any) -> tuple[dict[str, Any] | None, list[str]]:
|
| 128 |
+
"""Validate the teacher contract without trusting its resolved label."""
|
| 129 |
+
|
| 130 |
+
if not isinstance(payload, dict):
|
| 131 |
+
return None, ["invalid_json_object"]
|
| 132 |
+
if set(payload) != {"reasoning", "resolved_location", "audit_coordinates"}:
|
| 133 |
+
return None, ["unexpected_output_fields"]
|
| 134 |
+
try:
|
| 135 |
+
reasoning = validate_reasoning(payload.get("reasoning"))
|
| 136 |
+
resolved_location = validate_resolved_location(
|
| 137 |
+
payload.get("resolved_location"),
|
| 138 |
+
target_kind="address",
|
| 139 |
+
)
|
| 140 |
+
_validate_structured_address_shape(resolved_location)
|
| 141 |
+
latitude, longitude = _validate_audit_coordinates(payload.get("audit_coordinates"))
|
| 142 |
+
except ValueError as exc:
|
| 143 |
+
return None, [str(exc)]
|
| 144 |
+
if any(_COORDINATE_TEXT_RE.search(step) for step in reasoning):
|
| 145 |
+
return None, ["audit coordinates must not appear in reasoning"]
|
| 146 |
+
if _COORDINATE_TEXT_RE.search(resolved_location):
|
| 147 |
+
return None, ["audit coordinates must not appear in resolved_location"]
|
| 148 |
+
return {
|
| 149 |
+
"reasoning": reasoning,
|
| 150 |
+
# This is an audit field only. The final SFT label comes from frozen
|
| 151 |
+
# targets in build_reasoning_sft.py, never from this teacher response.
|
| 152 |
+
"teacher_resolved_location": resolved_location,
|
| 153 |
+
"teacher_audit_latitude": latitude,
|
| 154 |
+
"teacher_audit_longitude": longitude,
|
| 155 |
+
}, []
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def call_openai_sdk_chat_completion(
|
| 159 |
+
*,
|
| 160 |
+
base_url: str,
|
| 161 |
+
model: str,
|
| 162 |
+
api_key: str,
|
| 163 |
+
messages: list[dict[str, str]],
|
| 164 |
+
temperature: float,
|
| 165 |
+
max_tokens: int,
|
| 166 |
+
timeout_seconds: float,
|
| 167 |
+
json_mode: bool,
|
| 168 |
+
native_thinking: str,
|
| 169 |
+
reasoning_mode: str,
|
| 170 |
+
) -> tuple[str, dict[str, Any]]:
|
| 171 |
+
"""Call a compatible endpoint through the official SDK/httpx transport."""
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
from openai import OpenAI
|
| 175 |
+
except ImportError as exc:
|
| 176 |
+
raise RuntimeError(
|
| 177 |
+
"the openai package is required for --transport openai; "
|
| 178 |
+
"install it or use --transport urllib"
|
| 179 |
+
) from exc
|
| 180 |
+
|
| 181 |
+
client = OpenAI(api_key=api_key, base_url=base_url.rstrip("/"), timeout=timeout_seconds)
|
| 182 |
+
request: dict[str, Any] = {
|
| 183 |
+
"model": model,
|
| 184 |
+
"messages": messages,
|
| 185 |
+
"temperature": temperature,
|
| 186 |
+
"max_tokens": max_tokens,
|
| 187 |
+
}
|
| 188 |
+
if json_mode:
|
| 189 |
+
request["response_format"] = {"type": "json_object"}
|
| 190 |
+
extra_body: dict[str, Any] = {}
|
| 191 |
+
if native_thinking in {"on", "off"}:
|
| 192 |
+
extra_body["chat_template_kwargs"] = {"enable_thinking": native_thinking == "on"}
|
| 193 |
+
if reasoning_mode in {"on", "off"}:
|
| 194 |
+
extra_body["reasoning"] = {"enabled": reasoning_mode == "on"}
|
| 195 |
+
if extra_body:
|
| 196 |
+
request["extra_body"] = extra_body
|
| 197 |
+
|
| 198 |
+
started_at = time.perf_counter()
|
| 199 |
+
response = client.chat.completions.create(**request)
|
| 200 |
+
if not response.choices:
|
| 201 |
+
raise RuntimeError("endpoint returned no choices")
|
| 202 |
+
choice = response.choices[0]
|
| 203 |
+
content = choice.message.content
|
| 204 |
+
if not isinstance(content, str) or not content.strip():
|
| 205 |
+
raise RuntimeError("endpoint returned empty assistant content")
|
| 206 |
+
usage = response.usage.model_dump(mode="json") if response.usage is not None else None
|
| 207 |
+
return content, {
|
| 208 |
+
"returned_model": response.model or model,
|
| 209 |
+
"finish_reason": choice.finish_reason,
|
| 210 |
+
"usage": usage,
|
| 211 |
+
"latency_seconds": round(time.perf_counter() - started_at, 4),
|
| 212 |
+
"transport": "openai",
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def build_result(
|
| 217 |
+
row: dict[str, Any],
|
| 218 |
+
args: argparse.Namespace,
|
| 219 |
+
*,
|
| 220 |
+
api_key: str,
|
| 221 |
+
system_prompt: str,
|
| 222 |
+
) -> dict[str, Any]:
|
| 223 |
+
sample_id = clean_text(row["sample_id"])
|
| 224 |
+
query = clean_text(row["query"])
|
| 225 |
+
messages = teacher_messages(query, system_prompt)
|
| 226 |
+
if args.transport == "openai":
|
| 227 |
+
request = lambda: call_openai_sdk_chat_completion(
|
| 228 |
+
base_url=args.base_url,
|
| 229 |
+
model=args.model,
|
| 230 |
+
api_key=api_key,
|
| 231 |
+
messages=messages,
|
| 232 |
+
temperature=args.temperature,
|
| 233 |
+
max_tokens=args.max_tokens,
|
| 234 |
+
timeout_seconds=args.timeout_seconds,
|
| 235 |
+
json_mode=args.json_mode,
|
| 236 |
+
native_thinking=args.native_thinking,
|
| 237 |
+
reasoning_mode=args.reasoning_mode,
|
| 238 |
+
)
|
| 239 |
+
else:
|
| 240 |
+
request = lambda: call_chat_completion(
|
| 241 |
+
base_url=args.base_url,
|
| 242 |
+
model=args.model,
|
| 243 |
+
api_key=api_key,
|
| 244 |
+
messages=messages,
|
| 245 |
+
temperature=args.temperature,
|
| 246 |
+
max_tokens=args.max_tokens,
|
| 247 |
+
timeout_seconds=args.timeout_seconds,
|
| 248 |
+
json_mode=args.json_mode,
|
| 249 |
+
native_thinking=(args.native_thinking if args.native_thinking != "omit" else None),
|
| 250 |
+
reasoning_mode=(args.reasoning_mode if args.reasoning_mode != "omit" else None),
|
| 251 |
+
extra_headers={"User-Agent": "GeoCoding-Teacher-CoT/1.0"},
|
| 252 |
+
)
|
| 253 |
+
common = {
|
| 254 |
+
"sample_id": sample_id,
|
| 255 |
+
"generator_version": GENERATOR_VERSION,
|
| 256 |
+
"model": args.model,
|
| 257 |
+
"base_url": args.base_url.rstrip("/"),
|
| 258 |
+
"prompt_version": TEACHER_PROMPT_VERSION,
|
| 259 |
+
"native_thinking": args.native_thinking,
|
| 260 |
+
"reasoning_mode": args.reasoning_mode,
|
| 261 |
+
"transport": args.transport,
|
| 262 |
+
}
|
| 263 |
+
try:
|
| 264 |
+
raw_response, metadata, attempts = call_with_retries(
|
| 265 |
+
attempts=args.max_attempts,
|
| 266 |
+
request=request,
|
| 267 |
+
)
|
| 268 |
+
except Exception as exc: # noqa: BLE001 - retain one auditable failure row
|
| 269 |
+
return {
|
| 270 |
+
**common,
|
| 271 |
+
"status": "request_error",
|
| 272 |
+
"error": safe_error_text(exc),
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
payload, parse_error = parse_json_object(raw_response)
|
| 276 |
+
if parse_error:
|
| 277 |
+
return {
|
| 278 |
+
**common,
|
| 279 |
+
"status": "invalid_generation",
|
| 280 |
+
"raw_response": raw_response,
|
| 281 |
+
"validation_errors": [parse_error],
|
| 282 |
+
"request_attempts": attempts,
|
| 283 |
+
**metadata,
|
| 284 |
+
}
|
| 285 |
+
validated, validation_errors = validate_teacher_payload(payload)
|
| 286 |
+
if validation_errors or validated is None:
|
| 287 |
+
return {
|
| 288 |
+
**common,
|
| 289 |
+
"status": "invalid_generation",
|
| 290 |
+
"raw_response": raw_response,
|
| 291 |
+
"validation_errors": validation_errors,
|
| 292 |
+
"request_attempts": attempts,
|
| 293 |
+
**metadata,
|
| 294 |
+
}
|
| 295 |
+
return {
|
| 296 |
+
**common,
|
| 297 |
+
"status": "generated",
|
| 298 |
+
"reasoning": validated["reasoning"],
|
| 299 |
+
"teacher_resolved_location": validated["teacher_resolved_location"],
|
| 300 |
+
"teacher_audit_latitude": validated["teacher_audit_latitude"],
|
| 301 |
+
"teacher_audit_longitude": validated["teacher_audit_longitude"],
|
| 302 |
+
"raw_response": raw_response,
|
| 303 |
+
"request_attempts": attempts,
|
| 304 |
+
**metadata,
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def parse_args(argv: Iterable[str] | None = None) -> argparse.Namespace:
|
| 309 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 310 |
+
parser.add_argument("--input", type=Path, default=DEFAULT_INPUT)
|
| 311 |
+
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
|
| 312 |
+
parser.add_argument("--prompt", type=Path, default=TEACHER_PROMPT_PATH)
|
| 313 |
+
parser.add_argument("--base-url", default="http://127.0.0.1:8000/v1")
|
| 314 |
+
parser.add_argument("--model", required=True)
|
| 315 |
+
parser.add_argument("--api-key-env", default="LOCAL_OPENAI_API_KEY")
|
| 316 |
+
parser.add_argument(
|
| 317 |
+
"--transport",
|
| 318 |
+
choices=("openai", "urllib"),
|
| 319 |
+
default="openai",
|
| 320 |
+
help="HTTP transport. The OpenAI SDK is more compatible with protected API gateways.",
|
| 321 |
+
)
|
| 322 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 323 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
| 324 |
+
parser.add_argument("--max-tokens", type=int, default=1024)
|
| 325 |
+
parser.add_argument("--timeout-seconds", type=float, default=300.0)
|
| 326 |
+
parser.add_argument("--max-attempts", type=int, default=3)
|
| 327 |
+
parser.add_argument(
|
| 328 |
+
"--native-thinking",
|
| 329 |
+
choices=("omit", "off", "on"),
|
| 330 |
+
default="omit",
|
| 331 |
+
help="Optional Qwen/vLLM hidden-thinking control; omit for hosted GPT APIs.",
|
| 332 |
+
)
|
| 333 |
+
parser.add_argument(
|
| 334 |
+
"--reasoning-mode",
|
| 335 |
+
choices=("omit", "off", "on"),
|
| 336 |
+
default="omit",
|
| 337 |
+
help="Optional provider-specific hidden reasoning control; omit for hosted GPT APIs.",
|
| 338 |
+
)
|
| 339 |
+
parser.add_argument("--json-mode", action=argparse.BooleanOptionalAction, default=True)
|
| 340 |
+
parser.add_argument("--resume", action=argparse.BooleanOptionalAction, default=True)
|
| 341 |
+
parser.add_argument("--retry-non-generated", action="store_true")
|
| 342 |
+
parser.add_argument(
|
| 343 |
+
"--allow-mixed-models",
|
| 344 |
+
action="store_true",
|
| 345 |
+
help=(
|
| 346 |
+
"Allow an explicit cross-model retry to append newer rows to an existing "
|
| 347 |
+
"resume log; requires --resume and --retry-non-generated."
|
| 348 |
+
),
|
| 349 |
+
)
|
| 350 |
+
parser.add_argument("--overwrite", action="store_true")
|
| 351 |
+
parser.add_argument("--limit", type=int)
|
| 352 |
+
parser.add_argument("--progress-every", type=int, default=100)
|
| 353 |
+
parser.add_argument("--validate-only", action="store_true")
|
| 354 |
+
return parser.parse_args(list(argv) if argv is not None else None)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def main(argv: Iterable[str] | None = None) -> int:
|
| 358 |
+
args = parse_args(argv)
|
| 359 |
+
if args.workers < 1:
|
| 360 |
+
raise ValueError("workers must be at least 1")
|
| 361 |
+
if args.max_attempts < 1:
|
| 362 |
+
raise ValueError("max-attempts must be at least 1")
|
| 363 |
+
if args.limit is not None and args.limit < 0:
|
| 364 |
+
raise ValueError("limit must be non-negative")
|
| 365 |
+
if args.overwrite and args.resume:
|
| 366 |
+
args.resume = False
|
| 367 |
+
if args.allow_mixed_models and not (args.resume and args.retry_non_generated):
|
| 368 |
+
raise ValueError(
|
| 369 |
+
"--allow-mixed-models requires --resume and --retry-non-generated"
|
| 370 |
+
)
|
| 371 |
+
if args.output.exists() and not args.resume and not args.overwrite:
|
| 372 |
+
raise FileExistsError(f"output exists; use --resume or --overwrite: {args.output}")
|
| 373 |
+
|
| 374 |
+
system_prompt = load_system_prompt(args.prompt)
|
| 375 |
+
existing = (
|
| 376 |
+
load_jsonl_by_sample_id(args.output, allow_duplicate=True)
|
| 377 |
+
if args.resume and args.output.exists()
|
| 378 |
+
else {}
|
| 379 |
+
)
|
| 380 |
+
for sample_id, result in existing.items():
|
| 381 |
+
if (
|
| 382 |
+
clean_text(result.get("model"))
|
| 383 |
+
and result.get("model") != args.model
|
| 384 |
+
and not args.allow_mixed_models
|
| 385 |
+
):
|
| 386 |
+
raise ValueError(f"resume model mismatch for {sample_id}")
|
| 387 |
+
if (
|
| 388 |
+
clean_text(result.get("prompt_version"))
|
| 389 |
+
and result.get("prompt_version") != TEACHER_PROMPT_VERSION
|
| 390 |
+
):
|
| 391 |
+
raise ValueError(f"resume prompt mismatch for {sample_id}")
|
| 392 |
+
if clean_text(result.get("base_url")) and result.get("base_url") != args.base_url.rstrip("/"):
|
| 393 |
+
raise ValueError(f"resume base URL mismatch for {sample_id}")
|
| 394 |
+
if clean_text(result.get("transport")) and result.get("transport") != args.transport:
|
| 395 |
+
raise ValueError(f"resume transport mismatch for {sample_id}")
|
| 396 |
+
completed = {
|
| 397 |
+
sample_id
|
| 398 |
+
for sample_id, result in existing.items()
|
| 399 |
+
if not args.retry_non_generated or clean_text(result.get("status")) == "generated"
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
pending: list[dict[str, Any]] = []
|
| 403 |
+
seen: set[str] = set()
|
| 404 |
+
total = 0
|
| 405 |
+
for row_number, row in iter_jsonl(args.input):
|
| 406 |
+
sample_id, query = validate_input_row(row, row_number=row_number, path=args.input)
|
| 407 |
+
if sample_id in seen:
|
| 408 |
+
raise ValueError(f"duplicate sample_id in input: {sample_id}")
|
| 409 |
+
seen.add(sample_id)
|
| 410 |
+
total += 1
|
| 411 |
+
normalized_row = {"sample_id": sample_id, "query": query}
|
| 412 |
+
if sample_id not in completed:
|
| 413 |
+
pending.append(normalized_row)
|
| 414 |
+
if args.limit is not None:
|
| 415 |
+
pending = pending[: args.limit]
|
| 416 |
+
if args.validate_only:
|
| 417 |
+
print(f"Teacher input validation complete: total={total} pending={len(pending)}")
|
| 418 |
+
return 0
|
| 419 |
+
|
| 420 |
+
api_key = api_key_from_env(args.api_key_env, default="EMPTY")
|
| 421 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 422 |
+
mode = "a" if args.resume and args.output.exists() else "w"
|
| 423 |
+
counts: dict[str, int] = {}
|
| 424 |
+
with args.output.open(mode, encoding="utf-8", newline="") as handle:
|
| 425 |
+
with ThreadPoolExecutor(max_workers=args.workers) as executor:
|
| 426 |
+
futures = [
|
| 427 |
+
executor.submit(
|
| 428 |
+
build_result,
|
| 429 |
+
row,
|
| 430 |
+
args,
|
| 431 |
+
api_key=api_key,
|
| 432 |
+
system_prompt=system_prompt,
|
| 433 |
+
)
|
| 434 |
+
for row in pending
|
| 435 |
+
]
|
| 436 |
+
for index, future in enumerate(as_completed(futures), start=1):
|
| 437 |
+
result = future.result()
|
| 438 |
+
status = clean_text(result.get("status")) or "missing_status"
|
| 439 |
+
counts[status] = counts.get(status, 0) + 1
|
| 440 |
+
handle.write(json.dumps(result, ensure_ascii=False, separators=(",", ":")) + "\n")
|
| 441 |
+
handle.flush()
|
| 442 |
+
if args.progress_every > 0 and (
|
| 443 |
+
index % args.progress_every == 0 or index == len(pending)
|
| 444 |
+
):
|
| 445 |
+
print(
|
| 446 |
+
f"generated={index}/{len(pending)} statuses={json.dumps(counts, sort_keys=True)}",
|
| 447 |
+
flush=True,
|
| 448 |
+
)
|
| 449 |
+
print(
|
| 450 |
+
f"Teacher CoT generation complete: output={args.output} "
|
| 451 |
+
f"statuses={json.dumps(counts, sort_keys=True)}"
|
| 452 |
+
)
|
| 453 |
+
return 0
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
if __name__ == "__main__":
|
| 457 |
+
raise SystemExit(main())
|
api_share_v1/train/stage1/sft/prompts/teacher_spatial_reasoning_v1.txt
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an independent spherical spatial-reasoning teacher.
|
| 2 |
+
|
| 3 |
+
Use only the visible user request. The request is a synthetic coordinate
|
| 4 |
+
transformation problem, not a lookup task. Do not use or invent Wikidata,
|
| 5 |
+
OpenStreetMap, place names, addresses, entity identifiers, external facts, or
|
| 6 |
+
unstated geographic context.
|
| 7 |
+
|
| 8 |
+
Identify the supplied starting coordinate, interpret every movement in the
|
| 9 |
+
order stated, convert units when necessary, and reason on a sphere. Cardinal
|
| 10 |
+
directions map to bearings: north 0 degrees, east 90 degrees, south 180
|
| 11 |
+
degrees, and west 270 degrees. A later movement starts from the previous
|
| 12 |
+
intermediate point, never from the original point. Preserve the stated order
|
| 13 |
+
for multi-leg movements. Normalize longitude to the interval [-180, 180].
|
| 14 |
+
|
| 15 |
+
Write 2 to 5 concise reasoning steps. Do not put any numeric destination
|
| 16 |
+
coordinate, intermediate coordinate, geohash, or coordinate pair in the
|
| 17 |
+
reasoning array. The final reasoning step must state that the destination
|
| 18 |
+
coordinate has been resolved, without spelling out its numbers.
|
| 19 |
+
|
| 20 |
+
Return the teacher's estimated destination only in the separate audit field.
|
| 21 |
+
Do not include a `resolved_location` field: the final coordinate label is
|
| 22 |
+
materialized later from the local deterministic formula, not copied from the
|
| 23 |
+
teacher. `audit_coordinates` is not part of the reasoning output.
|
| 24 |
+
|
| 25 |
+
Return exactly one JSON object with exactly these keys and no others:
|
| 26 |
+
{"reasoning":["step 1","step 2"],"audit_coordinates":{"latitude":35.123456,"longitude":139.123456}}
|
| 27 |
+
|
| 28 |
+
Do not use Markdown, code fences, or any text outside the JSON object. Never
|
| 29 |
+
claim that an external place, map, database, benchmark, answer key, or hidden
|
| 30 |
+
reference was consulted.
|
api_share_v1/train/stage1/sft/prompts/teacher_structured_address_reasoning_v3.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an independent geographic reasoning and structured-address resolution teacher.
|
| 2 |
+
|
| 3 |
+
Use only the user's visible request to identify one real-world destination. Write 2 to 5 short reasoning steps. Each step must use a visible geographic clue, fact, relationship, or user intent. Do not invent a different entity, address component, role, date, or relationship.
|
| 4 |
+
|
| 5 |
+
For a resolved destination, return a complete broad-to-specific geographic address, not only a POI name. Include the supported country, administrative area when known, locality, sublocality when known, street, and named feature in that order. The named feature must be the final component. Preserve source spellings for address components shown in the request. A bare answer such as "Far Eastern Department Store Banqiao Store" is invalid; return the surrounding geographic structure as well.
|
| 6 |
+
|
| 7 |
+
Independently estimate the destination's GPS coordinates for audit. Put them only in audit_coordinates as numeric decimal degrees. Never mention, copy, or embed coordinates in a reasoning step or in resolved_location. audit_coordinates is separate audit evidence and is not part of the resolved address.
|
| 8 |
+
|
| 9 |
+
For a request that names a parent organization but explicitly asks for a child role or office, resolve the child and preserve that child role as the final named feature. Returning only the parent organization is insufficient.
|
| 10 |
+
|
| 11 |
+
If the visible request does not uniquely support one destination or does not provide enough information to form its geographic address and coordinates, set resolved_location to UNRESOLVED and do not guess. Such a response cannot satisfy the required numeric audit_coordinates contract and will be rejected for later review.
|
| 12 |
+
|
| 13 |
+
Return exactly one JSON object with exactly these keys and no others:
|
| 14 |
+
{"reasoning":["step 1","step 2"],"resolved_location":"country, administrative area, locality, street, named feature","audit_coordinates":{"latitude":25.0123,"longitude":121.4654}}
|
| 15 |
+
|
| 16 |
+
The reasoning array must contain 2 to 5 non-empty strings. The final step must state the resolved destination or state that it is unresolved. Latitude must be a JSON number from -90 to 90, and longitude must be a JSON number from -180 to 180. Do not mention benchmark names, task IDs, entity IDs, manifests, frozen truth, candidate lists, answer keys, or internal operation labels. Do not use Markdown, code fences, or any text outside the JSON object.
|
api_share_v1/train/stage1/sft/schema.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pure validation and message helpers for semantic-location reasoning SFT."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Iterable
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
PROMPT_VERSION = "semantic-location-reasoning-v1"
|
| 13 |
+
PROMPT_PATH = Path(__file__).with_name("prompts") / "semantic_location_reasoning_v1.txt"
|
| 14 |
+
MIN_REASONING_STEPS = 2
|
| 15 |
+
MAX_REASONING_STEPS = 5
|
| 16 |
+
MAX_REASONING_CHARS = 800
|
| 17 |
+
MAX_REASONING_STEP_CHARS = 320
|
| 18 |
+
MAX_RESOLVED_LOCATION_CHARS = 512
|
| 19 |
+
MAX_RESOLVED_ENTITY_CHARS = 256
|
| 20 |
+
|
| 21 |
+
_COORDINATE_RE = re.compile(
|
| 22 |
+
r"^latitude\s*=\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*"
|
| 23 |
+
r"longitude\s*=\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*$",
|
| 24 |
+
flags=re.IGNORECASE,
|
| 25 |
+
)
|
| 26 |
+
_HIDDEN_METADATA_RE = re.compile(
|
| 27 |
+
r"(?:\b(?:benchmark|benchb|entity\s*key|answer\s*key|frozen\s*(?:truth|coordinate|label)|"
|
| 28 |
+
r"manifest|candidate\s*list|task\s*(?:id|type))\b|\bosm:(?:node|way|relation):\d+\b|"
|
| 29 |
+
r"\bQ\d{2,}\b|\bB[1-4]\b)",
|
| 30 |
+
flags=re.IGNORECASE,
|
| 31 |
+
)
|
| 32 |
+
_WHITESPACE_RE = re.compile(r"\s+")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def clean_text(value: Any) -> str:
|
| 36 |
+
"""Collapse whitespace in a string and return an empty string otherwise."""
|
| 37 |
+
|
| 38 |
+
if not isinstance(value, str):
|
| 39 |
+
return ""
|
| 40 |
+
return _WHITESPACE_RE.sub(" ", value).strip()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _finite_coordinate(value: str, lower: float, upper: float) -> float:
|
| 44 |
+
number = float(value)
|
| 45 |
+
if not math.isfinite(number) or not lower <= number <= upper:
|
| 46 |
+
raise ValueError(f"coordinate {number!r} is outside [{lower}, {upper}]")
|
| 47 |
+
return number
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def parse_coordinate_location(value: Any) -> tuple[float, float] | None:
|
| 51 |
+
"""Parse the explicit coordinate label, or return None for an address label."""
|
| 52 |
+
|
| 53 |
+
text = clean_text(value)
|
| 54 |
+
match = _COORDINATE_RE.fullmatch(text)
|
| 55 |
+
if match is None:
|
| 56 |
+
return None
|
| 57 |
+
latitude = _finite_coordinate(match.group(1), -90.0, 90.0)
|
| 58 |
+
longitude = _finite_coordinate(match.group(2), -180.0, 180.0)
|
| 59 |
+
parts = (match.group(1).split(".", 1), match.group(2).split(".", 1))
|
| 60 |
+
if any(len(number_parts) != 2 or len(number_parts[1]) < 6 for number_parts in parts):
|
| 61 |
+
raise ValueError("derived coordinates must contain at least six decimal places")
|
| 62 |
+
return latitude, longitude
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def validate_reasoning(reasoning: Any) -> list[str]:
|
| 66 |
+
"""Normalize a visible reasoning trace without claiming it is factually true."""
|
| 67 |
+
|
| 68 |
+
if not isinstance(reasoning, list):
|
| 69 |
+
raise ValueError("reasoning must be a list")
|
| 70 |
+
if not MIN_REASONING_STEPS <= len(reasoning) <= MAX_REASONING_STEPS:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
f"reasoning must contain {MIN_REASONING_STEPS}-{MAX_REASONING_STEPS} steps"
|
| 73 |
+
)
|
| 74 |
+
normalized: list[str] = []
|
| 75 |
+
seen: set[str] = set()
|
| 76 |
+
total_chars = 0
|
| 77 |
+
for index, step in enumerate(reasoning, 1):
|
| 78 |
+
text = clean_text(step)
|
| 79 |
+
if not text:
|
| 80 |
+
raise ValueError(f"reasoning step {index} is empty")
|
| 81 |
+
if len(text) > MAX_REASONING_STEP_CHARS:
|
| 82 |
+
raise ValueError(f"reasoning step {index} is too long")
|
| 83 |
+
key = text.casefold()
|
| 84 |
+
if key in seen:
|
| 85 |
+
raise ValueError(f"reasoning step {index} duplicates an earlier step")
|
| 86 |
+
if _HIDDEN_METADATA_RE.search(text):
|
| 87 |
+
raise ValueError(f"reasoning step {index} contains hidden metadata")
|
| 88 |
+
seen.add(key)
|
| 89 |
+
normalized.append(text)
|
| 90 |
+
total_chars += len(text)
|
| 91 |
+
if total_chars > MAX_REASONING_CHARS:
|
| 92 |
+
raise ValueError("reasoning is too long")
|
| 93 |
+
return normalized
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def validate_query(value: Any) -> str:
|
| 97 |
+
"""Validate that the teacher-visible request contains no construction metadata."""
|
| 98 |
+
|
| 99 |
+
text = clean_text(value)
|
| 100 |
+
if not text:
|
| 101 |
+
raise ValueError("query must be non-empty")
|
| 102 |
+
if _HIDDEN_METADATA_RE.search(text):
|
| 103 |
+
raise ValueError("query contains hidden benchmark or entity metadata")
|
| 104 |
+
return text
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def validate_resolved_location(value: Any, *, target_kind: str | None = None) -> str:
|
| 108 |
+
"""Validate the shared address-or-coordinate intermediate representation."""
|
| 109 |
+
|
| 110 |
+
text = clean_text(value)
|
| 111 |
+
if not text:
|
| 112 |
+
raise ValueError("resolved_location must be non-empty")
|
| 113 |
+
if len(text) > MAX_RESOLVED_LOCATION_CHARS:
|
| 114 |
+
raise ValueError("resolved_location is too long")
|
| 115 |
+
if _HIDDEN_METADATA_RE.search(text):
|
| 116 |
+
raise ValueError("resolved_location contains hidden metadata")
|
| 117 |
+
coordinate = parse_coordinate_location(text)
|
| 118 |
+
normalized_kind = clean_text(target_kind).casefold()
|
| 119 |
+
coordinate_kinds = {"coordinate", "derived_point", "derived_spatial_point", "point_transform"}
|
| 120 |
+
address_kinds = {"address", "entity", "named_feature"}
|
| 121 |
+
if normalized_kind in coordinate_kinds and coordinate is None:
|
| 122 |
+
raise ValueError("coordinate target must use latitude=..., longitude=... form")
|
| 123 |
+
if normalized_kind in address_kinds and coordinate is not None:
|
| 124 |
+
raise ValueError("address target cannot use the explicit coordinate form")
|
| 125 |
+
lowered = text.casefold()
|
| 126 |
+
if coordinate is None and (lowered.startswith("latitude") or lowered.startswith("longitude")):
|
| 127 |
+
raise ValueError("coordinate-like resolved_location is malformed")
|
| 128 |
+
return text
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def validate_resolved_entity(value: Any) -> str:
|
| 132 |
+
"""Validate the teacher's independently inferred entity name audit field."""
|
| 133 |
+
|
| 134 |
+
text = clean_text(value)
|
| 135 |
+
if not text:
|
| 136 |
+
raise ValueError("resolved_entity must be non-empty")
|
| 137 |
+
if len(text) > MAX_RESOLVED_ENTITY_CHARS:
|
| 138 |
+
raise ValueError("resolved_entity is too long")
|
| 139 |
+
if _HIDDEN_METADATA_RE.search(text):
|
| 140 |
+
raise ValueError("resolved_entity contains hidden metadata")
|
| 141 |
+
if parse_coordinate_location(text) is not None:
|
| 142 |
+
raise ValueError("resolved_entity cannot be a coordinate")
|
| 143 |
+
return text
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def format_coordinate_location(latitude: Any, longitude: Any, *, precision: int = 6) -> str:
|
| 147 |
+
"""Format a coordinate label accepted by the shared output contract."""
|
| 148 |
+
|
| 149 |
+
if precision < 6:
|
| 150 |
+
raise ValueError("coordinate precision must be at least six decimal places")
|
| 151 |
+
if isinstance(latitude, bool) or isinstance(longitude, bool):
|
| 152 |
+
raise ValueError("coordinates must be numeric, not boolean")
|
| 153 |
+
lat = float(latitude)
|
| 154 |
+
lon = float(longitude)
|
| 155 |
+
if not math.isfinite(lat) or not -90.0 <= lat <= 90.0:
|
| 156 |
+
raise ValueError("invalid latitude")
|
| 157 |
+
if not math.isfinite(lon) or not -180.0 <= lon <= 180.0:
|
| 158 |
+
raise ValueError("invalid longitude")
|
| 159 |
+
return f"latitude={lat:.{precision}f}, longitude={lon:.{precision}f}"
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def load_system_prompt(path: Path = PROMPT_PATH) -> str:
|
| 163 |
+
prompt = path.read_text(encoding="utf-8").strip()
|
| 164 |
+
if not prompt:
|
| 165 |
+
raise ValueError(f"empty reasoning prompt: {path}")
|
| 166 |
+
return prompt
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def assistant_json(reasoning: Iterable[str], resolved_location: str) -> str:
|
| 170 |
+
"""Serialize the assistant target with stable key order."""
|
| 171 |
+
|
| 172 |
+
normalized_reasoning = validate_reasoning(list(reasoning))
|
| 173 |
+
normalized_location = validate_resolved_location(resolved_location)
|
| 174 |
+
return json.dumps(
|
| 175 |
+
{"reasoning": normalized_reasoning, "resolved_location": normalized_location},
|
| 176 |
+
ensure_ascii=False,
|
| 177 |
+
separators=(",", ":"),
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def make_training_messages(
|
| 182 |
+
query: str,
|
| 183 |
+
reasoning: Iterable[str],
|
| 184 |
+
resolved_location: str,
|
| 185 |
+
*,
|
| 186 |
+
system_prompt: str | None = None,
|
| 187 |
+
) -> list[dict[str, str]]:
|
| 188 |
+
"""Build the exact three-message row consumed by ms-swift."""
|
| 189 |
+
|
| 190 |
+
user = validate_query(query)
|
| 191 |
+
return [
|
| 192 |
+
{"role": "system", "content": system_prompt or load_system_prompt()},
|
| 193 |
+
{"role": "user", "content": user},
|
| 194 |
+
{"role": "assistant", "content": assistant_json(reasoning, resolved_location)},
|
| 195 |
+
]
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def make_compact_training_messages(
|
| 199 |
+
query: str,
|
| 200 |
+
reasoning: Iterable[str],
|
| 201 |
+
resolved_location: str,
|
| 202 |
+
) -> list[dict[str, str]]:
|
| 203 |
+
"""Build the compact on-disk row; the launcher injects the system prompt."""
|
| 204 |
+
|
| 205 |
+
return [
|
| 206 |
+
{"role": "user", "content": validate_query(query)},
|
| 207 |
+
{"role": "assistant", "content": assistant_json(reasoning, resolved_location)},
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _validate_message_objects(messages: Any) -> None:
|
| 212 |
+
if not isinstance(messages, list):
|
| 213 |
+
raise ValueError("training row messages must be a list")
|
| 214 |
+
if not all(
|
| 215 |
+
isinstance(message, dict) and set(message) == {"role", "content"}
|
| 216 |
+
for message in messages
|
| 217 |
+
):
|
| 218 |
+
raise ValueError("each message must contain exactly role and content")
|
| 219 |
+
if not all(
|
| 220 |
+
isinstance(message["content"], str) and message["content"].strip()
|
| 221 |
+
for message in messages
|
| 222 |
+
):
|
| 223 |
+
raise ValueError("training message content must be non-empty strings")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _validate_assistant_content(content: str) -> None:
|
| 227 |
+
try:
|
| 228 |
+
assistant = json.loads(content)
|
| 229 |
+
except json.JSONDecodeError as exc:
|
| 230 |
+
raise ValueError("assistant content is not JSON") from exc
|
| 231 |
+
if not isinstance(assistant, dict) or set(assistant) != {"reasoning", "resolved_location"}:
|
| 232 |
+
raise ValueError("assistant JSON has an unexpected schema")
|
| 233 |
+
validate_reasoning(assistant["reasoning"])
|
| 234 |
+
validate_resolved_location(assistant["resolved_location"])
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def validate_compact_training_row(row: Any) -> dict[str, Any]:
|
| 238 |
+
"""Validate the compact source row stored in the repository dataset."""
|
| 239 |
+
|
| 240 |
+
if not isinstance(row, dict) or set(row) != {"id", "messages"}:
|
| 241 |
+
raise ValueError("training row must contain exactly id and messages")
|
| 242 |
+
sample_id = clean_text(row.get("id"))
|
| 243 |
+
if not sample_id:
|
| 244 |
+
raise ValueError("training row id must be non-empty")
|
| 245 |
+
messages = row["messages"]
|
| 246 |
+
_validate_message_objects(messages)
|
| 247 |
+
if len(messages) != 2 or [message["role"] for message in messages] != [
|
| 248 |
+
"user",
|
| 249 |
+
"assistant",
|
| 250 |
+
]:
|
| 251 |
+
raise ValueError("compact training messages must have roles user/assistant")
|
| 252 |
+
validate_query(messages[0]["content"])
|
| 253 |
+
_validate_assistant_content(messages[1]["content"])
|
| 254 |
+
return row
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def validate_training_row(row: Any) -> dict[str, Any]:
|
| 258 |
+
"""Validate the runtime model-facing row after system-prompt injection."""
|
| 259 |
+
|
| 260 |
+
if not isinstance(row, dict) or set(row) != {"id", "messages"}:
|
| 261 |
+
raise ValueError("training row must contain exactly id and messages")
|
| 262 |
+
sample_id = clean_text(row.get("id"))
|
| 263 |
+
if not sample_id:
|
| 264 |
+
raise ValueError("training row id must be non-empty")
|
| 265 |
+
messages = row["messages"]
|
| 266 |
+
_validate_message_objects(messages)
|
| 267 |
+
if len(messages) != 3:
|
| 268 |
+
raise ValueError("training row must contain system, user, and assistant messages")
|
| 269 |
+
if [message["role"] for message in messages] != ["system", "user", "assistant"]:
|
| 270 |
+
raise ValueError("training messages must have roles system/user/assistant")
|
| 271 |
+
validate_query(messages[1]["content"])
|
| 272 |
+
_validate_assistant_content(messages[2]["content"])
|
| 273 |
+
return row
|