6262 typer_factory ,
6363)
6464from ._framework import Argument , Option
65- from ._output import _dataclass_to_dict , out
65+ from ._output import OutputFormat , _dataclass_to_dict , out
6666from ._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+
875898def _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+ )
904914def 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 (
0 commit comments