Skip to content

Commit a5277cf

Browse files
[CLI] Snapshot by default in hf jobs stats, add -f/--follow (#5090)
* [CLI] Snapshot by default in hf jobs stats, add -f/--follow * fix snapshot hanging on jobs that send no metrics * align fetch_job_metrics with fetch_job_logs (follow param) * add a hint when hf jobs stats -f ends * fix stats -f end hint claiming jobs stopped
1 parent 83ce8b0 commit a5277cf

4 files changed

Lines changed: 103 additions & 30 deletions

File tree

‎docs/source/en/guides/cli.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1892,6 +1892,8 @@ This command runs the job and shows the logs. You can pass `--detach` to run the
18921892
>>> hf jobs stats
18931893
# View resources usage stats and metrics of some jobs
18941894
>>> hf jobs stats [job_ids]...
1895+
# Follow live stats until the jobs complete
1896+
>>> hf jobs stats -f [job_ids]...
18951897

18961898
# Cancel a job
18971899
>>> hf jobs cancel <job_id>

‎docs/source/en/package_reference/cli.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2314,7 +2314,7 @@ $ hf jobs [OPTIONS] COMMAND [ARGS]...
23142314
* `run`: Run a Job.
23152315
* `scheduled`: Create and manage scheduled Jobs on the Hub.
23162316
* `ssh`: SSH into a running Job.
2317-
* `stats`: Fetch the resource usage statistics and metrics of Jobs
2317+
* `stats`: Fetch the resource usage statistics and metrics of Jobs.
23182318
* `uv`: Run UV scripts (Python with inline dependencies) on HF infrastructure.
23192319
* `wait`: Wait for one or more Jobs to reach a terminal state.
23202320

@@ -3045,7 +3045,10 @@ Learn more
30453045

30463046
### `hf jobs stats`
30473047

3048-
Fetch the resource usage statistics and metrics of Jobs
3048+
Fetch the resource usage statistics and metrics of Jobs.
3049+
3050+
By default, prints a snapshot of the current stats and exits (non-blocking).
3051+
Use --follow/-f to display live stats until the Jobs complete.
30493052

30503053
**Usage**:
30513054

@@ -3059,12 +3062,15 @@ $ hf jobs stats [OPTIONS] [JOB_IDS]...
30593062

30603063
**Options**:
30613064

3065+
* `-f, --follow`: Follow stats output (live view until the Jobs complete). Without this flag, a single snapshot is printed.
30623066
* `--namespace TEXT`: The namespace where the job will be running. Defaults to the current user's namespace.
30633067
* `--token TEXT`: A User Access Token generated from https://huggingface.co/settings/tokens.
30643068
* `--help`: Show this message and exit.
30653069

30663070
Examples
3071+
$ hf jobs stats
30673072
$ hf jobs stats <job_id>
3073+
$ hf jobs stats -f <job_id>
30683074

30693075
Learn more
30703076
Use `hf <command> --help` for more information about a command.

‎src/huggingface_hub/cli/jobs.py‎

Lines changed: 75 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@
6262
typer_factory,
6363
)
6464
from ._framework import Argument, Option
65-
from ._output import _dataclass_to_dict, out
65+
from ._output import OutputFormat, _dataclass_to_dict, out
6666
from ._uv_script_header import TABLE_NAME, UvScriptHeader, load_uv_script
6767

6868

@@ -872,41 +872,68 @@ def _clear_line(n: int) -> None:
872872
print(LINE_UP, end=LINE_CLEAR)
873873

874874

875+
def _format_job_stats_rows(job_id: str, metrics: dict[str, Any], table_headers: list[str]) -> list[list[str | int]]:
876+
row: list[str | int] = [
877+
job_id,
878+
f"{metrics['cpu_usage_pct']}%",
879+
round(metrics["cpu_millicores"] / 1000.0, 1),
880+
f"{round(100 * metrics['memory_used_bytes'] / metrics['memory_total_bytes'], 2)}%",
881+
f"{_format_size(metrics['memory_used_bytes'])}B / {_format_size(metrics['memory_total_bytes'])}B",
882+
f"{_format_size(metrics['rx_bps'])}bps / {_format_size(metrics['tx_bps'])}bps",
883+
]
884+
if metrics["gpus"] and isinstance(metrics["gpus"], dict):
885+
rows: list[list[str | int]] = [row] + [[""] * len(row) for _ in range(len(metrics["gpus"]) - 1)]
886+
for row, gpu_id in zip(rows, sorted(metrics["gpus"])):
887+
gpu = metrics["gpus"][gpu_id]
888+
row += [
889+
f"{gpu['utilization']}%",
890+
f"{round(100 * gpu['memory_used_bytes'] / gpu['memory_total_bytes'], 2)}%",
891+
f"{_format_size(gpu['memory_used_bytes'])}B / {_format_size(gpu['memory_total_bytes'])}B",
892+
]
893+
return rows
894+
row += ["N/A"] * (len(table_headers) - len(row))
895+
return [row]
896+
897+
875898
def _get_jobs_stats_rows(
876899
job_id: str, metrics_stream: Iterable[dict[str, Any]], table_headers: list[str]
877900
) -> Iterable[tuple[bool, str, list[list[str | int]]]]:
878901
for metrics in metrics_stream:
879-
row = [
880-
job_id,
881-
f"{metrics['cpu_usage_pct']}%",
882-
round(metrics["cpu_millicores"] / 1000.0, 1),
883-
f"{round(100 * metrics['memory_used_bytes'] / metrics['memory_total_bytes'], 2)}%",
884-
f"{_format_size(metrics['memory_used_bytes'])}B / {_format_size(metrics['memory_total_bytes'])}B",
885-
f"{_format_size(metrics['rx_bps'])}bps / {_format_size(metrics['tx_bps'])}bps",
886-
]
887-
if metrics["gpus"] and isinstance(metrics["gpus"], dict):
888-
rows = [row] + [[""] * len(row) for _ in range(len(metrics["gpus"]) - 1)]
889-
for row, gpu_id in zip(rows, sorted(metrics["gpus"])):
890-
gpu = metrics["gpus"][gpu_id]
891-
row += [
892-
f"{gpu['utilization']}%",
893-
f"{round(100 * gpu['memory_used_bytes'] / gpu['memory_total_bytes'], 2)}%",
894-
f"{_format_size(gpu['memory_used_bytes'])}B / {_format_size(gpu['memory_total_bytes'])}B",
895-
]
896-
else:
897-
row += ["N/A"] * (len(table_headers) - len(row))
898-
rows = [row]
899-
yield False, job_id, rows
902+
yield False, job_id, _format_job_stats_rows(job_id, metrics, table_headers)
900903
yield True, job_id, []
901904

902905

903-
@jobs_cli.command("stats", examples=["hf jobs stats <job_id>"])
906+
@jobs_cli.command(
907+
"stats",
908+
examples=[
909+
"hf jobs stats",
910+
"hf jobs stats <job_id>",
911+
"hf jobs stats -f <job_id>",
912+
],
913+
)
904914
def jobs_stats(
905915
job_ids: JobIdsArg = None,
916+
follow: Annotated[
917+
bool,
918+
Option(
919+
"-f",
920+
"--follow",
921+
help="Follow stats output (live view until the Jobs complete). Without this flag, a single snapshot is printed.",
922+
),
923+
] = False,
906924
namespace: NamespaceOpt = None,
907925
token: TokenOpt = None,
908926
) -> None:
909-
"""Fetch the resource usage statistics and metrics of Jobs"""
927+
"""Fetch the resource usage statistics and metrics of Jobs.
928+
929+
By default, prints a snapshot of the current stats and exits (non-blocking).
930+
Use --follow/-f to display live stats until the Jobs complete.
931+
"""
932+
if follow and out.mode != OutputFormat.human:
933+
raise CLIError(
934+
f"`--follow` displays a live terminal view and is not supported with '{out.mode.value}' output."
935+
" Run without `--follow` to get a snapshot."
936+
)
910937
if job_ids is not None:
911938
parsed_ids = []
912939
for job_id in job_ids:
@@ -937,6 +964,27 @@ def jobs_stats(
937964
"GPU MEM %",
938965
"GPU MEM USAGE",
939966
]
967+
if not follow:
968+
969+
def fetch_latest_metrics(job_id: str) -> dict[str, Any] | None:
970+
return next(iter(api.fetch_job_metrics(job_id=job_id, namespace=namespace)), None)
971+
972+
with multiprocessing.pool.ThreadPool(len(job_ids)) as pool:
973+
latest_metrics = pool.map(fetch_latest_metrics, job_ids)
974+
items = []
975+
for job_id, metrics in zip(job_ids, latest_metrics):
976+
if metrics is None:
977+
out.warning(f"No stats available for Job {job_id}. Is it running?")
978+
else:
979+
items.append({"job_id": job_id, **metrics})
980+
if out.mode == OutputFormat.human and items:
981+
rows = [row for item in items for row in _format_job_stats_rows(item["job_id"], item, table_headers)]
982+
out.text(_tabulate(rows, headers=table_headers))
983+
job_refs = " ".join(f"{namespace}/{item['job_id']}" for item in items)
984+
out.hint(f"Use `hf jobs stats -f {job_refs}` to follow live stats.")
985+
else:
986+
out.table(items, id_key="job_id")
987+
return
940988
with multiprocessing.pool.ThreadPool(len(job_ids)) as pool:
941989
rows_per_job_id: dict[str, list[list[str | int]]] = {}
942990
for job_id in job_ids:
@@ -952,7 +1000,7 @@ def jobs_stats(
9521000
kwargs_list = [
9531001
{
9541002
"job_id": job_id,
955-
"metrics_stream": api.fetch_job_metrics(job_id=job_id, namespace=namespace),
1003+
"metrics_stream": api.fetch_job_metrics(job_id=job_id, namespace=namespace, follow=True),
9561004
"table_headers": table_headers,
9571005
}
9581006
for job_id in job_ids
@@ -968,6 +1016,8 @@ def jobs_stats(
9681016
total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]]
9691017
print(_tabulate(total_rows, headers=table_headers))
9701018
last_update_time = now
1019+
job_refs = " ".join(f"{namespace}/{job_id}" for job_id in job_ids)
1020+
out.hint(f"Stream ended. Run `hf jobs inspect {job_refs}` to check the final status (e.g. COMPLETED or ERROR).")
9711021

9721022

9731023
@jobs_cli.command(

‎src/huggingface_hub/hf_api.py‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8515,7 +8515,8 @@ def _stream_sse_events(
85158515
# Drop params after the first attempt: the start_event_idx dedup
85168516
# requires a stable replay prefix, which `tail` would break.
85178517
params = None
8518-
if on_iteration_end is not None and on_iteration_end():
8518+
# no-follow: a single attempt, never loop back
8519+
if not follow or (on_iteration_end is not None and on_iteration_end()):
85198520
break
85208521

85218522
def _fetch_space_logs_sse(
@@ -12174,10 +12175,11 @@ def fetch_job_metrics(
1217412175
*,
1217512176
job_id: str,
1217612177
namespace: str | None = None,
12178+
follow: bool = False,
1217712179
token: bool | str | None = None,
1217812180
) -> Iterable[dict[str, Any]]:
1217912181
"""
12180-
Fetch all the live metrics from a compute Job on Hugging Face infrastructure.
12182+
Fetch the live metrics from a compute Job on Hugging Face infrastructure.
1218112183

1218212184
Args:
1218312185
job_id (`str`):
@@ -12186,6 +12188,10 @@ def fetch_job_metrics(
1218612188
namespace (`str`, *optional*):
1218712189
The namespace where the Job is running. Defaults to the current user's namespace.
1218812190

12191+
follow (`bool`, *optional*):
12192+
If `True`, stream metrics in real-time until the job completes (blocking).
12193+
If `False` (default), fetch only the current metrics and return (non-blocking).
12194+
1218912195
token (`bool` or `str`, *optional*):
1219012196
A valid user access token. If not provided, the locally saved token will be used, which is the
1219112197
recommended authentication method. Set to `False` to disable authentication.
@@ -12214,6 +12220,10 @@ def fetch_job_metrics(
1221412220
},
1221512221
"replica": "57vr7"
1221612222
}
12223+
12224+
>>> # Stream metrics until the job completes
12225+
>>> for metrics in fetch_job_metrics(job_id=job.id, follow=True):
12226+
... print(metrics)
1221712227
```
1221812228
"""
1221912229
# - there is one "metric" event every second, like this:
@@ -12225,15 +12235,20 @@ def fetch_job_metrics(
1222512235
# - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming
1222612236
# - there is a ": keep-alive" every 30 seconds
1222712237
seconds_between_events = 1
12228-
yield from self._fetch_running_job_sse(
12238+
metrics_stream = self._fetch_running_job_sse(
1222912239
job_id=job_id,
1223012240
route="metrics",
1223112241
timeout=10 * seconds_between_events,
1223212242
skip_previous_events_on_retry=False,
1223312243
tolerated_status_codes=(406, 500),
1223412244
namespace=namespace,
1223512245
token=token,
12246+
follow=follow,
1223612247
)
12248+
if follow:
12249+
yield from metrics_stream
12250+
else: # the stream has no history: its first sample is the current one
12251+
yield from itertools.islice(metrics_stream, 1)
1223712252

1223812253
def list_jobs(
1223912254
self,

0 commit comments

Comments
 (0)