Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 10,850 Bytes
2a2e170 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | """Derive tags for a session trajectory.
``tag_session(trajectory)`` β ``list[str]``. Pure function. No filtering, no
mutation β tags are purely metadata so downstream pipelines can slice the raw
SFT dataset (``where 'hf_job:succeeded' in tags``) without re-reading trajectories.
Tag namespaces (all tags are ``"<namespace>:<value>"`` strings):
* ``tool:<name>`` β every tool called at least once (``tool:hf_jobs``, β¦)
* ``outcome:<end>`` β ``completed`` / ``errored`` / ``interrupted`` /
``ongoing`` / ``doom_loop`` / ``context_exceeded``
* ``hf_job:<facet>`` β ``submitted``, ``succeeded``, ``failed``,
``multi`` (>1), ``oom``, ``push_to_hub``
* ``gpu:<kind>`` β ``none``, ``t4``, ``a10g``, ``a100``, ``l40s``,
``h100``, plus ``gpu:multi`` for x2/x4/x8 flavors
* ``sandbox:<facet>`` β ``created``, ``gpu``, ``cpu``, ``long_lived`` (>30 min)
* ``feedback:<kind>`` β ``up``, ``down``, ``mixed``, ``none``
* ``model:<family>`` β ``opus`` / ``sonnet`` / ``haiku`` / ``kimi`` /
``gpt`` / ``deepseek`` / ``qwen`` / ``other``
* ``turns:<bucket>`` β ``short`` (<5) / ``medium`` (5β20) / ``long`` (>20)
* ``cost:<bucket>`` β ``low`` (<$0.10) / ``med`` (<$1) / ``high``
* ``task:<kind>`` β ``training`` / ``inference`` / ``data_prep`` /
``research_only`` (heuristic on tools + scripts)
Tags are deduplicated before returning.
"""
from __future__ import annotations
from typing import Any, Iterable
# Flavor β GPU-family mapping. Keep conservative; unknown flavors β "none".
_GPU_FAMILY = {
"cpu-basic": "none", "cpu-upgrade": "none",
"t4-small": "t4", "t4-medium": "t4",
"l4x1": "l40s", "l4x4": "l40s",
"l40sx1": "l40s", "l40sx4": "l40s", "l40sx8": "l40s",
"a10g-small": "a10g", "a10g-large": "a10g",
"a10g-largex2": "a10g", "a10g-largex4": "a10g",
"a100-large": "a100", "a100x2": "a100",
"a100x4": "a100", "a100x8": "a100",
"h100": "h100", "h100x8": "h100",
}
# Substrings that count a flavor as multi-GPU.
_MULTI_GPU_MARKERS = ("x2", "x4", "x8")
# Tool names that don't touch training/inference or sandbox/jobs. If a session
# only used these, we tag it research_only.
_RESEARCH_ONLY_TOOLS = {
"research", "github_find_examples", "github_read_file", "github_list_repos",
"hf_papers", "explore_hf_docs", "fetch_hf_docs", "hub_repo_details",
"plan", "hf_inspect_dataset", "web_search",
}
# Tool names that signal data manipulation workflows.
_DATA_PREP_TOOLS = {"hf_inspect_dataset", "dataset_tools", "hub_repo_details"}
def _model_family(model_name: str | None) -> str:
if not model_name:
return "other"
n = model_name.lower()
if "opus" in n:
return "opus"
if "sonnet" in n:
return "sonnet"
if "haiku" in n:
return "haiku"
if "kimi" in n:
return "kimi"
if "gpt" in n:
return "gpt"
if "deepseek" in n:
return "deepseek"
if "qwen" in n:
return "qwen"
if "llama" in n:
return "llama"
return "other"
def _turns_bucket(n: int) -> str:
if n < 5:
return "short"
if n <= 20:
return "medium"
return "long"
def _cost_bucket(cost_usd: float) -> str:
if cost_usd < 0.10:
return "low"
if cost_usd < 1.0:
return "med"
return "high"
def _flavor_to_gpu_tags(flavor: str) -> list[str]:
family = _GPU_FAMILY.get(flavor, "none")
tags = [f"gpu:{family}"]
if any(m in flavor for m in _MULTI_GPU_MARKERS):
tags.append("gpu:multi")
return tags
def _has_oom_signal(tool_outputs: Iterable[str]) -> bool:
for out in tool_outputs:
if not isinstance(out, str):
continue
low = out.lower()
if "outofmemoryerror" in low or "cuda out of memory" in low or "oom" in low:
return True
return False
def _infer_task_tag(
tool_names: set[str],
hf_job_submit_scripts: list[str],
) -> str | None:
"""Return a ``task:*`` tag or None if we can't tell.
Heuristic order: training > inference > data_prep > research_only.
"""
# training: any hf_jobs script with a Trainer/SFT/training keyword, OR uses
# hf_jobs at all and a script mentions training APIs.
for script in hf_job_submit_scripts:
low = script.lower()
if any(k in low for k in (
"sftconfig", "sfttrainer", "trainer(", "trainingarguments",
"grpo", "dpo", ".train(", "transformers import",
"trainer import", "fine-tune", "finetune",
)):
return "training"
# inference: sessions that use inference tools but never hf_jobs/sandbox
uses_compute = bool(tool_names & {"hf_jobs", "sandbox_create", "sandbox_exec"})
if not uses_compute and tool_names & {"inference", "generate", "run_inference"}:
return "inference"
# data_prep: primarily dataset tools and no training/inference
if tool_names & _DATA_PREP_TOOLS and not uses_compute:
return "data_prep"
# research_only: every tool used is in the research allow-list
if tool_names and tool_names <= _RESEARCH_ONLY_TOOLS:
return "research_only"
return None
def tag_session(trajectory: dict) -> list[str]:
"""Derive tags from a session trajectory. Pure function."""
tags: set[str] = set()
events: list[dict] = trajectory.get("events") or []
messages: list[dict] = trajectory.get("messages") or []
model_name: str | None = trajectory.get("model_name")
# model
tags.add(f"model:{_model_family(model_name)}")
# turns
user_turns = sum(1 for m in messages if m.get("role") == "user")
tags.add(f"turns:{_turns_bucket(user_turns)}")
# cost + tool-name enumeration + outcome detection
cost_usd = 0.0
tool_names: set[str] = set()
tool_outputs: list[str] = []
hf_job_submit_count = 0
hf_job_submit_scripts: list[str] = []
hf_job_success_count = 0
hf_job_fail_count = 0
hf_job_push_to_hub = False
gpu_tags_seen: set[str] = set()
# Outcome is the *last* terminal signal. Seed with "ongoing" β overridden
# if we see a terminal event.
outcome = "ongoing"
had_error = False
had_doom_loop = False
had_compact = False
feedback_up = 0
feedback_down = 0
sandbox_created = False
sandbox_hardware: str | None = None
sandbox_lifetime_s: int | None = None
for ev in events:
et = ev.get("event_type")
data = ev.get("data") or {}
if et == "llm_call":
cost_usd += float(data.get("cost_usd") or 0.0)
elif et == "tool_call":
name = data.get("tool")
if name:
tool_names.add(name)
elif et == "tool_output":
out = data.get("output")
if isinstance(out, str):
tool_outputs.append(out)
elif et == "hf_job_submit":
hf_job_submit_count += 1
if data.get("push_to_hub"):
hf_job_push_to_hub = True
flavor = data.get("flavor") or "cpu-basic"
for t in _flavor_to_gpu_tags(flavor):
gpu_tags_seen.add(t)
elif et == "hf_job_complete":
final = (data.get("final_status") or "").lower()
if final in ("completed", "succeeded", "success"):
hf_job_success_count += 1
elif final in ("failed", "error", "timeout", "cancelled"):
hf_job_fail_count += 1
elif et == "sandbox_create":
sandbox_created = True
sandbox_hardware = data.get("hardware")
elif et == "sandbox_destroy":
lt = data.get("lifetime_s")
if isinstance(lt, (int, float)):
sandbox_lifetime_s = int(lt)
elif et == "feedback":
rating = data.get("rating")
if rating == "up":
feedback_up += 1
elif rating == "down":
feedback_down += 1
elif et == "error":
had_error = True
elif et == "turn_complete":
if not had_error:
outcome = "completed"
elif et == "interrupted":
outcome = "interrupted"
elif et == "compacted":
had_compact = True
elif et == "tool_log":
log_text = (data.get("log") or "").lower()
if "doom loop" in log_text:
had_doom_loop = True
if had_error and outcome not in ("completed", "interrupted"):
outcome = "errored"
tags.add(f"outcome:{outcome}")
if had_doom_loop:
tags.add("outcome:doom_loop")
if had_compact:
tags.add("outcome:context_exceeded")
# tools
for name in tool_names:
tags.add(f"tool:{name}")
# hf_jobs facets
if hf_job_submit_count >= 1:
tags.add("hf_job:submitted")
if hf_job_submit_count > 1:
tags.add("hf_job:multi")
if hf_job_success_count > 0:
tags.add("hf_job:succeeded")
if hf_job_fail_count > 0:
tags.add("hf_job:failed")
if hf_job_push_to_hub:
tags.add("hf_job:push_to_hub")
if _has_oom_signal(tool_outputs):
tags.add("hf_job:oom")
# gpu tags (from all submitted jobs)
tags.update(gpu_tags_seen)
if "gpu:none" in tags and len(gpu_tags_seen) > 1:
# If any GPU flavor was used, drop the "none" tag for clarity.
tags.discard("gpu:none")
# sandbox facets
if sandbox_created:
tags.add("sandbox:created")
if sandbox_hardware:
fam = _GPU_FAMILY.get(sandbox_hardware, "none")
tags.add("sandbox:cpu" if fam == "none" else "sandbox:gpu")
if sandbox_lifetime_s is not None and sandbox_lifetime_s > 1800:
tags.add("sandbox:long_lived")
# feedback
if feedback_up and feedback_down:
tags.add("feedback:mixed")
elif feedback_up:
tags.add("feedback:up")
elif feedback_down:
tags.add("feedback:down")
else:
tags.add("feedback:none")
# cost bucket
tags.add(f"cost:{_cost_bucket(cost_usd)}")
# task heuristic (needs scripts β pull from the hf_job_submit events'
# matching tool_call arguments in the event list).
for ev in events:
if ev.get("event_type") == "tool_call":
data = ev.get("data") or {}
if data.get("tool") == "hf_jobs":
args = data.get("arguments") or {}
script = args.get("script") or args.get("command") or ""
if isinstance(script, str):
hf_job_submit_scripts.append(script)
task_tag = _infer_task_tag(tool_names, hf_job_submit_scripts)
if task_tag:
tags.add(f"task:{task_tag}")
return sorted(tags)
|