-
Notifications
You must be signed in to change notification settings - Fork 762
[Jobs] Add huggingface-cli jobs
commands
#3211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
+1,771
−0
Merged
Changes from 7 commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
4836c04
jobs
lhoestq 682a789
style
lhoestq af05c27
docs
lhoestq 3895c8e
mypy
lhoestq 3661cb7
style
lhoestq 13f17c8
minor
lhoestq 5e99d64
remove hfjobs mentions
lhoestq 7efe998
add huggingface-cli jobs uv commands
lhoestq ab8511e
add some uv options
lhoestq 3c00292
add test
lhoestq 3136ef4
fix for 3.8
lhoestq 9fc3c78
Update src/huggingface_hub/commands/jobs/uv.py
davanstrien fd926b5
move to HfApi
lhoestq 1bf5f66
minor
lhoestq aefb493
more comments
lhoestq 31a3d97
uv run local_script.py
lhoestq f7c8be9
lucain's comments
lhoestq 541aa6a
more lucain's comments
lhoestq 251e719
Apply suggestions from code review
lhoestq 97a856b
style
lhoestq 1102968
minor
lhoestq 99b538a
Remove JobUrl and add url in JobInfo directly
Wauplin 53fb0aa
Apply suggestions from code review
lhoestq 4e3523d
add namespace arg
lhoestq 5db3b42
fix wrong job url
lhoestq 76588ef
add missing methods at top level
lhoestq 63dd90f
add docs
lhoestq bfd326a
uv script url as env, not secret
lhoestq c9ab2f1
rename docs
lhoestq cf59dca
update test
lhoestq da1d40d
again
lhoestq 334d831
improve docs
lhoestq 028d32a
Merge branch 'main' into jobs
Wauplin fed7195
add image arg to run_uv_job
lhoestq eaaa6a1
List flavors from SpaceHardware
Wauplin c7660d7
Merge branch 'jobs' of github.com:huggingface/huggingface_hub into jobs
Wauplin af0e9fb
add to overview
lhoestq e6043ae
remove zero GPU from flavors
Wauplin c444391
add JobInfo etc. from _jobs_api in top level __init__
lhoestq ea6579a
add package_reference doc page
lhoestq 3f6a2f7
minor - link JobInfo in docs
lhoestq 3e049db
JobInfo docstring
lhoestq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
# Copyright 2025 The HuggingFace Team. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
"""Contains commands to interact with jobs on the Hugging Face Hub. | ||
|
||
Usage: | ||
# run a job | ||
huggingface-cli jobs run image command | ||
""" | ||
|
||
from argparse import _SubParsersAction | ||
|
||
from huggingface_hub.commands import BaseHuggingfaceCLICommand | ||
from huggingface_hub.commands.jobs.cancel import CancelCommand | ||
from huggingface_hub.commands.jobs.inspect import InspectCommand | ||
from huggingface_hub.commands.jobs.logs import LogsCommand | ||
from huggingface_hub.commands.jobs.ps import PsCommand | ||
from huggingface_hub.commands.jobs.run import RunCommand | ||
from huggingface_hub.utils import logging | ||
|
||
|
||
logger = logging.get_logger(__name__) | ||
|
||
|
||
class JobsCommands(BaseHuggingfaceCLICommand): | ||
@staticmethod | ||
def register_subcommand(parser: _SubParsersAction): | ||
jobs_parser = parser.add_parser("jobs", help="Commands to interact with your huggingface.co jobs.") | ||
jobs_subparsers = jobs_parser.add_subparsers(help="huggingface.co jobs related commands") | ||
|
||
# Register commands | ||
InspectCommand.register_subcommand(jobs_subparsers) | ||
LogsCommand.register_subcommand(jobs_subparsers) | ||
PsCommand.register_subcommand(jobs_subparsers) | ||
RunCommand.register_subcommand(jobs_subparsers) | ||
CancelCommand.register_subcommand(jobs_subparsers) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import os | ||
from typing import Union | ||
|
||
|
||
def tabulate(rows: list[list[Union[str, int]]], headers: list[str]) -> str: | ||
Wauplin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Inspired by: | ||
|
||
- stackoverflow.com/a/8356620/593036 | ||
- stackoverflow.com/questions/9535954/printing-lists-as-tabular-data | ||
""" | ||
col_widths = [max(len(str(x)) for x in col) for col in zip(*rows, headers)] | ||
terminal_width = max(os.get_terminal_size().columns, len(headers) * 12) | ||
while len(headers) + sum(col_widths) > terminal_width: | ||
col_to_minimize = col_widths.index(max(col_widths)) | ||
col_widths[col_to_minimize] //= 2 | ||
if len(headers) + sum(col_widths) <= terminal_width: | ||
col_widths[col_to_minimize] = terminal_width - sum(col_widths) - len(headers) + col_widths[col_to_minimize] | ||
row_format = ("{{:{}}} " * len(headers)).format(*col_widths) | ||
lines = [] | ||
lines.append(row_format.format(*headers)) | ||
lines.append(row_format.format(*["-" * w for w in col_widths])) | ||
for row in rows: | ||
row_format_args = [ | ||
str(x)[: col_width - 3] + "..." if len(str(x)) > col_width else str(x) | ||
for x, col_width in zip(row, col_widths) | ||
] | ||
lines.append(row_format.format(*row_format_args)) | ||
return "\n".join(lines) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
from argparse import Namespace, _SubParsersAction | ||
from typing import Optional | ||
|
||
import requests | ||
|
||
from huggingface_hub import whoami | ||
from huggingface_hub.utils import build_hf_headers | ||
|
||
from .. import BaseHuggingfaceCLICommand | ||
|
||
|
||
class CancelCommand(BaseHuggingfaceCLICommand): | ||
@staticmethod | ||
def register_subcommand(parser: _SubParsersAction) -> None: | ||
run_parser = parser.add_parser("jobs cancel", help="Cancel a Job") | ||
lhoestq marked this conversation as resolved.
Show resolved
Hide resolved
|
||
run_parser.add_argument("job_id", type=str, help="Job ID") | ||
run_parser.add_argument( | ||
"--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens" | ||
) | ||
run_parser.set_defaults(func=CancelCommand) | ||
|
||
def __init__(self, args: Namespace) -> None: | ||
self.job_id: str = args.job_id | ||
self.token: Optional[str] = args.token or None | ||
|
||
def run(self) -> None: | ||
username = whoami(self.token)["name"] | ||
headers = build_hf_headers(token=self.token) | ||
requests.post( | ||
f"https://huggingface.co/api/jobs/{username}/{self.job_id}/cancel", | ||
headers=headers, | ||
).raise_for_status() | ||
lhoestq marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import json | ||
from argparse import Namespace, _SubParsersAction | ||
from typing import Optional | ||
|
||
import requests | ||
|
||
from huggingface_hub import whoami | ||
from huggingface_hub.utils import build_hf_headers | ||
|
||
from .. import BaseHuggingfaceCLICommand | ||
|
||
|
||
class InspectCommand(BaseHuggingfaceCLICommand): | ||
@staticmethod | ||
def register_subcommand(parser: _SubParsersAction) -> None: | ||
run_parser = parser.add_parser("inspect", help="Display detailed information on one or more Jobs") | ||
run_parser.add_argument( | ||
"--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens" | ||
) | ||
run_parser.add_argument("jobs", nargs="...", help="The jobs to inspect") | ||
run_parser.set_defaults(func=InspectCommand) | ||
|
||
def __init__(self, args: Namespace) -> None: | ||
self.token: Optional[str] = args.token or None | ||
self.jobs: list[str] = args.jobs | ||
lhoestq marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def run(self) -> None: | ||
username = whoami(self.token)["name"] | ||
headers = build_hf_headers(token=self.token) | ||
inspections = [ | ||
requests.get( | ||
f"https://huggingface.co/api/jobs/{username}/{job}", | ||
headers=headers, | ||
).json() | ||
for job in self.jobs | ||
] | ||
print(json.dumps(inspections, indent=4)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
import json | ||
import time | ||
from argparse import Namespace, _SubParsersAction | ||
from typing import Optional | ||
|
||
import requests | ||
|
||
from huggingface_hub import whoami | ||
from huggingface_hub.utils import build_hf_headers | ||
|
||
from .. import BaseHuggingfaceCLICommand | ||
|
||
|
||
class LogsCommand(BaseHuggingfaceCLICommand): | ||
@staticmethod | ||
def register_subcommand(parser: _SubParsersAction) -> None: | ||
run_parser = parser.add_parser("logs", help="Fetch the logs of a Job") | ||
run_parser.add_argument("job_id", type=str, help="Job ID") | ||
run_parser.add_argument("-t", "--timestamps", action="store_true", help="Show timestamps") | ||
run_parser.add_argument( | ||
"--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens" | ||
) | ||
run_parser.set_defaults(func=LogsCommand) | ||
|
||
def __init__(self, args: Namespace) -> None: | ||
self.job_id: str = args.job_id | ||
self.timestamps: bool = args.timestamps | ||
self.token: Optional[str] = args.token or None | ||
|
||
def run(self) -> None: | ||
username = whoami(self.token)["name"] | ||
headers = build_hf_headers(token=self.token) | ||
requests.get( | ||
f"https://huggingface.co/api/jobs/{username}/{self.job_id}", | ||
headers=headers, | ||
).raise_for_status() | ||
|
||
logging_started = False | ||
logging_finished = False | ||
job_finished = False | ||
# - We need to retry because sometimes the /logs doesn't return logs when the job just started. | ||
# (for example it can return only two lines: one for "Job started" and one empty line) | ||
# - Timeouts can happen in case of build errors | ||
# - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming | ||
# - Infinite empty log stream can happen in case of build error | ||
# (the logs stream is infinite and empty except for the Job started message) | ||
# - there is a ": keep-alive" every 30 seconds | ||
lhoestq marked this conversation as resolved.
Show resolved
Hide resolved
|
||
while True: | ||
try: | ||
resp = requests.get( | ||
f"https://huggingface.co/api/jobs/{username}/{self.job_id}/logs", | ||
headers=headers, | ||
stream=True, | ||
timeout=120, | ||
) | ||
log = None | ||
for line in resp.iter_lines(chunk_size=1): | ||
line = line.decode("utf-8") | ||
if line and line.startswith("data: {"): | ||
data = json.loads(line[len("data: ") :]) | ||
# timestamp = data["timestamp"] | ||
if not data["data"].startswith("===== Job started"): | ||
logging_started = True | ||
log = data["data"] | ||
print(log) | ||
logging_finished = logging_started | ||
except requests.exceptions.ChunkedEncodingError: | ||
# Response ended prematurely | ||
break | ||
except KeyboardInterrupt: | ||
break | ||
except requests.exceptions.ConnectionError as err: | ||
is_timeout = err.__context__ and isinstance(err.__context__.__cause__, TimeoutError) | ||
if logging_started or not is_timeout: | ||
raise | ||
if logging_finished or job_finished: | ||
break | ||
job_status = requests.get( | ||
f"https://huggingface.co/api/jobs/{username}/{self.job_id}", | ||
headers=headers, | ||
).json() | ||
if "status" in job_status and job_status["status"]["stage"] not in ("RUNNING", "UPDATING"): | ||
job_finished = True | ||
time.sleep(1) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.