Repository navigation
Add HuggingFace Jobs step operator - #4520
Conversation
Adds a new step operator to the existing HuggingFace integration that runs individual ZenML steps as HF Jobs. The operator submits Docker containers to HF infrastructure via run_job(), polls until completion with inspect_job(), streams logs, and handles cancellation on interrupt. Key features: - Config/Settings/Flavor classes following Modal/Vertex patterns - Stack validation requiring remote artifact store + container registry - Environment variables sent as HF encrypted secrets by default - Per-step overrides for hardware flavor, timeout, and namespace - Token resolution chain: config → HF_TOKEN env → cached login - Runtime guard for huggingface_hub Jobs API availability
Adds a new docs page following the Modal step operator template, covering prerequisites, registration, token resolution, env-as-secrets behavior, per-step settings, and config reference tables. Updates the step operators overview table, TOC navigation, and GitBook redirects.
- Fix stage.value AttributeError when HF API returns string instead of JobStage enum in error cases - Publish HF Job URL as step run metadata (orchestrator_url, orchestrator_logs_url, orchestrator_run_id) so it appears as a clickable link in the ZenML dashboard - Document public container registry requirement (HF Jobs cannot pull from private registries like GCR/ECR/ACR) - Document HF Spaces Docker images as an alternative registry option - Add GPU hardware section with CUDA base image instructions - Fix step_operator=True typos to step_operator="<NAME>" in docs
Address code review findings: improve version checking with actionable error messages, prevent HF token leakage in plain env vars, use public SpaceHardware import path, add polling retry/backoff with best-effort job cancellation, make log streaming opt-in, fix test portability for CI environments without huggingface_hub, and align docs with behavior.
…ep-operator # Conflicts: # docs/book/component-guide/step-operators/README.md
Adapt the HuggingFace Jobs step operator to the new submit/get_status/ cancel interface introduced in PR #4515. This is required for dynamic pipeline support. - Add submit() that creates the HF Job and returns immediately, persisting job identity in step run metadata - Add get_status() that maps HF JobStage to ExecutionStatus - Add cancel() with best-effort cancellation via cancel_job - Override wait() to preserve HF-specific polling (configurable interval, transient error retry, optional log streaming) - Refactor launch() as thin legacy wrapper (submit + wait) - Add _get_job_identity() helper for metadata recovery - Add 16 new unit tests for get_status, cancel, and _get_job_identity
|
|
- Use _HF_TOKEN_ENV_KEYS constant in _resolve_token() instead of hardcoding env var names (DRY fix) - Stream logs without materializing full history into memory each poll - Remove unnecessary hasattr(stage, "value") guards (JobStage is always an enum) - Add clarifying comment on cancel() call in launch()
|
✅ No broken links found! |
There was a problem hiding this comment.
Acknowledging that a lot of mocking going on here. Can strip it down even more if needed.
Documentation Link Check Results✅ Absolute links check passed |
Remove documented RuntimeError from get_status docstring (raised by helper, not directly) and fix 404 SDK docs URL in HF Jobs page.
|
|
|
|
|
✅ No broken links found! |
|
|
|
|
|
|
|
|
|
🔒 This PR has been automatically closed due to 4 weeks of inactivity. |
|
|
safoinme
left a comment
There was a problem hiding this comment.
Thanks for this, Alex. HF Jobs is a nice addition, and the async lifecycle is the right shape. I went through it against current develop (the branch is ~7 months behind and conflicts in huggingface/__init__.py and the step-operators README; both are trivial to resolve).
The main blocker: wait() crashes on the first poll that finds a job still running (see the inline comment on L626), so static pipelines fail and leave the HF job running. Several other paths also return or fail without cancelling the remote job (polling errors, a swallowed metadata-publish failure, stop signals caught as transient errors). Valid Jobs hardware flavors like h200 are rejected, and every job gets the operator's HF token by default.
What I ran on the merge with develop: pytest tests/unit/integrations/huggingface/step_operators (33 passed) and mypy src/zenml/integrations/huggingface (clean). I couldn't do a live HF Jobs run. An end-to-end run (static + dynamic, including a cancel) would be great before merging, since the unit-test fakes hide the main bug.
| logger.debug( | ||
| "HuggingFace Job %s stage: %s. Polling again in %ss.", | ||
| job_id, | ||
| stage.value, |
There was a problem hiding this comment.
This crashes on the first poll that finds the job still running. inspect_job returns a JobInfo whose status.stage is a plain str, not a JobStage. JobInfo.__init__ does JobStatus(stage=status["stage"]) with no conversion, in both 0.36.x and 1.x. The == checks still work because JobStage is a str-enum. But stage.value here (and at L618) raises AttributeError, outside the inner try.
On develop the static launcher always goes submit → wait, so any step that isn't already COMPLETED at the first poll ends up FAILED. Nothing cancels it, so the HF job keeps running and billing. I reproduced this by feeding wait() real JobInfo(**payload) objects (RUNNING → COMPLETED).
Suggest normalizing once with stage = JobStage(job_info.status.stage), or logging the string, plus one wait() test built from a real JobInfo.
There was a problem hiding this comment.
Fixed in 32469d08f0. Dropped the custom polling loop in wait() in favor of BaseStepOperator.wait(), and normalized stage formatting in get_status() safely for both plain strings and Enum values (never calling .value directly on job_info.status.stage). Added a wait() test using real JobInfo(**payload) objects (SCHEDULING → RUNNING → COMPLETED) and verified live on HF Jobs.
| consecutive_errors, | ||
| poll_err, | ||
| ) | ||
| return ExecutionStatus.FAILED |
There was a problem hiding this comment.
When polling fails three times in a row, this returns FAILED but doesn't cancel the job, so it may still be running on HF. The cancel in launch() was meant to cover that, but on develop launch() never runs when submit() is implemented. The launcher only falls back to launch_with_allocation on NotImplementedError (step_launcher.py ~L537-582).
The base wait() handles this case by falling back to the ZenML server's step status. Could we drop this override and rely on the base wait() + get_status()? If the custom loop is needed, at least cancel before returning FAILED. Then launch() can go, or cleanup_step_submission can be used for the cancel.
There was a problem hiding this comment.
Fixed in 32469d08f0. Dropped the custom polling loop and the dead launch() method, and delegated wait() to BaseStepOperator.wait() (so transient poll errors fall back to the ZenML server's step status instead of prematurely returning FAILED while the HF job keeps running). Kept a thin wrapper in wait() that calls self.cancel(step_run) on stop/interrupt signals or STOPPED/STOPPING status.
| token=token, | ||
| ) | ||
| consecutive_errors = 0 | ||
| except Exception as poll_err: |
There was a problem hiding this comment.
except Exception also catches RunStoppedException / RunInterruptedException, which SignalHandler raises on SIGTERM/SIGINT. A user stop that lands during inspect_job is counted as "transient error 1/3", and polling continues until the job ends. The same happens in the log-streaming except at L593, where it's swallowed at debug level. Could we narrow both to network/HTTP errors (requests.RequestException, HfHubHTTPError) and cancel the job on the way out?
There was a problem hiding this comment.
Fixed in 32469d08f0. With the custom polling and log-streaming loops removed, wait() now explicitly catches (KeyboardInterrupt, RunStoppedException, RunInterruptedException) around super().wait(step_run), calls self.cancel(step_run), and re-raises (and also cancels if super().wait() returns STOPPED/STOPPING). Verified live by sending SIGINT during wait() and confirming inspect_job() reports stage='CANCELED'.
| step_run_id=info.step_run_id, | ||
| step_run_metadata={self.id: step_metadata}, | ||
| ) | ||
| except Exception: |
There was a problem hiding this comment.
If publishing the metadata fails, we only log at debug level. The job is already created, but its ID exists only on the in-memory step run. The dynamic runner, or any other process calling get_status/cancel, then hits "Cannot find HuggingFace Job ID" and can neither monitor nor stop it. Modal's operator handles the same case by terminating and re-raising. Could we cancel job.id here (logging the job URL if that fails) and re-raise?
There was a problem hiding this comment.
Fixed in 32469d08f0. submit() now matches ModalStepOperator: if publish_step_run_metadata (or local metadata update) fails, it calls cancel_job for job.id (logging job.id and job.url via logger.exception if cancel also fails) and re-raises. Covered by unit tests.
| METADATA_ORCHESTRATOR_URL: Uri(str(job.url)), | ||
| METADATA_ORCHESTRATOR_LOGS_URL: Uri(str(job.url)), | ||
| } | ||
| if namespace: |
There was a problem hiding this comment.
When namespace isn't set, nothing is stored. Every later inspect_job / fetch_job_logs / cancel_job then does an extra whoami call to resolve it, doubling API calls per poll. Recovery under a different token would also look in the wrong namespace. job.owner.name is on the returned JobInfo; could we always persist that?
There was a problem hiding this comment.
Fixed in 32469d08f0. submit() now persists settings.namespace or job.owner.name in both server metadata and info.step_run.run_metadata. Confirmed in live E2E runs that whoami-v2 is called only once at run_job and zero times during subsequent polls.
| if self.config.stream_logs: | ||
| try: | ||
| count = 0 | ||
| for count, line in enumerate( |
There was a problem hiding this comment.
fetch_job_logs follows the stream until the job finishes, so with stream_logs=True the first call blocks and the poll interval stops applying. Also:
- The generator swallows
KeyboardInterruptinternally. log_offsetis only updated after a full pass, so a dropped stream re-prints its lines.- Concurrent dynamic steps never stream at all, since only
get_status()is called.
Maybe stream once, outside the status loop, and say in the docs which modes stream? Minor: the docs intro says logs stream, but stream_logs defaults to False.
There was a problem hiding this comment.
Fixed in 32469d08f0. Removed stream_logs along with the custom wait() loop — fetch_job_logs also diverged between hub 0.36.x (always blocking, no follow arg) and 1.x (follow=False default), and didn't apply to dynamic pipelines anyway. Updated the docs to explain that ZenML captures step logs normally and links directly to the HF Job URL in step metadata.
| image = info.get_image(key=HUGGINGFACE_JOBS_DOCKER_IMAGE_KEY) | ||
| token = _resolve_token(self.config) | ||
|
|
||
| hardware_flavor_str = ( |
There was a problem hiding this comment.
ResourceSettings (e.g. gpu_count=1) is silently ignored here, so the step runs on cpu-basic with no message. A warning pointing to hardware_flavor, like SageMaker does, would save some confusion.
There was a problem hiding this comment.
Fixed in 32469d08f0. Added a warning in submit() when not info.config.resource_settings.empty, pointing users to hardware_flavor (matching SagemakerStepOperator), plus unit test coverage and a note in the docs.
| for key in _HF_TOKEN_ENV_KEYS: | ||
| secrets[key] = token | ||
|
|
||
| job_name = f"zenml-{info.run_name}-{info.pipeline_step_name}"[:63] |
There was a problem hiding this comment.
Nits:
job_nameis computed and logged but never passed torun_job.- The
"job_name"metadata key actually stores the job ID. settings.x or self.config.xis redundant, becauseget_settings()already merges the component config into the settings._best_effort_cancel(cancel_fn: Any, ...)could just callcancel_jobdirectly.
There was a problem hiding this comment.
All four fixed in 32469d08f0:
- Dropped unused
job_namecomputation (log step/run name directly). - Renamed the metadata key from
"job_name"to"hf_job_id"(STEP_JOB_ID_METADATA_KEY). - Read
settings.hardware_flavor,settings.timeout, andsettings.namespacedirectly instead ofsettings.x or self.config.x. _best_effort_cancelnow imports and callscancel_jobdirectly instead of takingcancel_fn: Any.
| "increases HF API calls and may cause transient log-fetch errors " | ||
| "during job initialization. Enable for real-time step visibility", | ||
| ) | ||
| poll_interval_seconds: float = Field( |
There was a problem hiding this comment.
This accepts 0, negative values, NaN and inf. 0 makes the loop spin, and a negative value makes time.sleep raise after the job has been submitted. Suggest Field(gt=0, allow_inf_nan=False, ...).
There was a problem hiding this comment.
Removed poll_interval_seconds in 32469d08f0 since wait() now delegates polling to BaseStepOperator.wait().
| ) | ||
|
|
||
|
|
||
| class FakeJobStage(enum.Enum): |
There was a problem hiding this comment.
This fake is a real Enum, but the SDK hands back a plain string for the stage. That mismatch is exactly what hides the stage.value crash in wait(). INITIALIZING also isn't a real JobStage. Likewise, the HfFolder stub hides the hub 1.x break. Rather than more helper tests, I'd swap a good part of this file for a few submit / wait / get_status tests that build real JobInfo(**payload) objects and patch only the network calls. wait(), submit(), the validator and the hardware resolution currently have no coverage.
There was a problem hiding this comment.
Rebuilt the test suite in 32469d08f0: constructs real huggingface_hub.JobInfo(**payload) objects (plain-string status.stage) when huggingface_hub is installed, mirrors that exact plain-string shape with real stages (SCHEDULING, RUNNING, COMPLETED, ERROR, CANCELED, DELETED) and get_token when running in minimal CI without huggingface_hub, and adds coverage for submit(), wait() (including stop/interrupt cancel), get_status(), cancel(), and validator. Verified 36/36 passing across huggingface_hub==0.36.2, huggingface_hub==1.33.0, and uninstalled CI mode.
…review # Conflicts: # docs/book/component-guide/step-operators/README.md # src/zenml/integrations/huggingface/__init__.py
|
Thanks for the thorough review, @safoinme! Merged latest
Unit tests (36 passed) also verified against real |
VIDEO DEMO
Summary
Adds a new HuggingFace Jobs step operator to the existing
huggingfaceintegration, allowing individual ZenML pipeline steps to run as HF Jobs on Hugging Face infrastructure with CPU/GPU support.huggingface_hub's Jobs API (run_job,inspect_job,cancel_job), delegates polling and server-status fallback toBaseStepOperator.wait(), cancels the remote job on stop/interrupt signals or metadata-publish failures, and persistshf_job_id,hf_job_namespace(falling back tojob.owner.name), and clickable job URLs in step run metadata.submit()/get_status()/wait()/cancel(), supporting both static and dynamic pipelines.huggingface-jobsflavor with component-level config (tokenviaSecretField,pass_env_as_secrets) and per-step settings (hardware_flavor,timeout,namespace). Hardware flavor strings (e.g.,cpu-basic,a10g-small,a100x4,h200) are passed straight through torun_job.token→huggingface_hub.get_token()(OIDC,HF_TOKEN,hf auth logincache across hub 0.x and 1.x) → legacyHUGGING_FACE_HUB_TOKEN. The operator token is used only for Jobs API calls and is not injected into job containers. Environment variables are sent as HF encrypted secrets by default (pass_env_as_secrets=True), and step-suppliedHF_TOKEN/HUGGING_FACE_HUB_TOKENare always routed to HF secrets. Warns ifHF_DEBUGis enabled when submitting secrets.submit,wait(includingKeyboardInterrupt/RunStoppedException/RunInterruptedException/STOPPEDcancellation),get_statuswith real plain-stringJobInfo.status.stage,cancel,validator,split_environment,_resolve_token, and_check_hf_jobs_availability. Tested withhuggingface_hub==0.36.2,huggingface_hub==1.33.0, and withouthuggingface_hubinstalled.Files changed
step_operators/huggingface_jobs_step_operator.py,flavors/huggingface_jobs_step_operator_flavor.pyhuggingface/__init__.py,huggingface/flavors/__init__.py,huggingface/step_operators/__init__.pytests/unit/integrations/huggingface/step_operators/test_huggingface_jobs_step_operator.pystep-operators/huggingface-jobs.md,step-operators/README.md,toc.md,.gitbook.yamlRequirements
huggingface_hub >= 0.34.0, < 2.0.0(runtime-checked; basehuggingfaceintegration pin left unchanged to avoid a breaking dependency bump)Test plan
huggingface_hub==0.36.2,huggingface_hub==1.33.0, and uninstalled CI mode (36 tests —pytest tests/unit/integrations/huggingface/step_operators/)ruff,pydoclint,mypy, andlychee --offlineclean on changed fileshuggingface_hub==1.33.0,cpu-basic, GCS artifact store, public Docker Hub repo):submit→wait): passed, 7 polls,whoamicalled once, artifact round-tripped, confirmed operator HF token not leaked into container, metadata persisted (hf_job_id=6b06f9bfb6a90bbe997db923)step.submit(...)): passed, asyncget_status()polling +future.load()artifact round-trip (hf_job_id=6b06fa7db6a90bbe997dbbcd)SIGINTcancel duringwait(): remote HF job canceled and confirmedstage='CANCELED'viainspect_job()(hf_job_id=6b06fadfd91f621b93082d55)