Repository navigation
[doc][train] Correct Ray Train doc claims that the source contradicts - #66895
Conversation
There was a problem hiding this comment.
Code Review
This pull request updates the Ray Train documentation to reflect that Ray Train V2 is the default starting in Ray 2.51. It also refines several user guides and API details, including checkpoint storage behavior, GPU scaling configurations, PyTorch Lightning strategy settings and tested versions, Hugging Face Accelerate deprecation/removal timelines, asynchronous validation metric conversion, temporary directory usage for checkpoints, and elastic training failure/preemption configurations. There are no review comments, so I have no feedback to provide.
6c6db91 to
69e0221
Compare
69e0221 to
00e4d53
Compare
|
|
||
| * You typically use `TorchTrainer` for training, but you can also use it for validation, as this example does. Training and validation can then have different resource requirements, such as A100 GPUs for training and A10G GPUs for validation. | ||
| * The validation training function returns its metrics directly from worker 0 instead of calling `ray.train.report`. Access them through `result.return_value`. These values can't be `torch` tensors and must be Python-based, as with `ray.train.report`. | ||
| * The validation training function returns its metrics directly from worker 0 instead of calling `ray.train.report`. Access them through `result.return_value`. As with `ray.train.report`, these values can't contain `torch` tensors, so convert them to Python objects first, for example with `.item()`. |
There was a problem hiding this comment.
I would rewrite this.
This is a rough summary that should rewrite
A TorchTrainer can be spawned from Ray.train.report validation function. The question is how the validation functions metrics should be passed back. Both Ray.train.report and results.metrics or return metrics and results.return_value work.
The return version is suggested as it's viewed as more elegant. See test async checkpoint validation script for example (see older versions for a report variant)
There was a problem hiding this comment.
Rewording this to cover both ways the validation run can pass metrics back, and to say why return_value is the one to use:
| * The validation training function returns its metrics directly from worker 0 instead of calling `ray.train.report`. Access them through `result.return_value`. As with `ray.train.report`, these values can't contain `torch` tensors, so convert them to Python objects first, for example with `.item()`. | |
| * The validation training function returns its metrics from worker 0, and `validation_fn` reads them from `result.return_value`. Returning metrics from the training function works starting in Ray 2.56. As with `ray.train.report`, the return value can't contain `torch` tensors, so convert them to Python objects first, for example with `.item()`. | |
| * You can also call `ray.train.report` in the validation training function and read the metrics from `result.metrics`. Ray Train keeps reported metrics only when they come with a checkpoint, so this approach needs a placeholder checkpoint reported with `ray.train.CheckpointUploadMode.NO_UPLOAD`. Returning the metrics avoids the placeholder checkpoint, so use `return_value`. |
Source: release/train_tests/async_checkpointing_validation_benchmark/test_async_checkpointing_validation_benchmark.py returns {"score": ...} and reads result.return_value["score"]. Versions before #62021 used the report variant. report_handler.py drops metrics from reports that have no checkpoint.
| Each `report` call blocks until the previous call's checkpoint upload completes, then starts a new checkpoint upload thread. Ray Train does this to avoid accumulating too many upload threads and potentially running out of memory. | ||
|
|
||
| Because `report` returns without waiting for the checkpoint upload to complete, you must keep the local checkpoint directory alive until the checkpoint upload completes. You can't use a temporary directory that Ray Train may delete before the upload finishes, for example from `tempfile.TemporaryDirectory`. `report` also has a `delete_local_checkpoint_after_upload` parameter, which defaults to `True` if `checkpoint_upload_mode` is `ray.train.CheckpointUploadMode.ASYNC`. | ||
| Because `report` returns without waiting for the checkpoint upload to complete, you must keep the local checkpoint directory alive until the checkpoint upload completes. You can't use a directory that's deleted before the upload finishes, such as a `tempfile.TemporaryDirectory`, which Python deletes when its `with` block exits. The following example uses `tempfile.mkdtemp` instead. `report` also has a `delete_local_checkpoint_after_upload` parameter, which defaults to `True` if `checkpoint_upload_mode` is `ray.train.CheckpointUploadMode.ASYNC`, so Ray Train deletes the local checkpoint directory after the upload completes. |
There was a problem hiding this comment.
I don't think this is true. There are two options
Sync will wait for the checkpoint to be copied to the storage path. This means that you can use a "with temp file" for the checkpoint as the file won't be deleted as report needs to finish first.
Async won't wait and report won't block (other than waiting for all other ranks to finish). Therefore with temp file doesn't work and the temp file needs to be manually closed.
Again this is a rough description which should be confirmed using the test async checkpointing script
There was a problem hiding this comment.
Checked this against context.py and the async checkpointing benchmark. The behavior matches the PR's wording, but the contrast with sync is worth saying, and Ray Train cleans up the mkdtemp directory itself, so readers don't need to:
| Because `report` returns without waiting for the checkpoint upload to complete, you must keep the local checkpoint directory alive until the checkpoint upload completes. You can't use a directory that's deleted before the upload finishes, such as a `tempfile.TemporaryDirectory`, which Python deletes when its `with` block exits. The following example uses `tempfile.mkdtemp` instead. `report` also has a `delete_local_checkpoint_after_upload` parameter, which defaults to `True` if `checkpoint_upload_mode` is `ray.train.CheckpointUploadMode.ASYNC`, so Ray Train deletes the local checkpoint directory after the upload completes. | |
| Because `report` returns before the checkpoint upload completes, keep the local checkpoint directory alive until the upload finishes. Don't write the checkpoint to a `tempfile.TemporaryDirectory`, because Python deletes that directory when its `with` block exits, which can happen before the upload finishes. A `tempfile.TemporaryDirectory` works with `ray.train.CheckpointUploadMode.SYNC`, because `report` returns only after the upload completes. The following example uses `tempfile.mkdtemp` instead. `report` also has a `delete_local_checkpoint_after_upload` parameter, which defaults to `True` with `ray.train.CheckpointUploadMode.ASYNC`, so Ray Train deletes the local checkpoint directory after the upload completes. |
Source: in context.py, report() uploads inline for SYNC and submits the upload to a single-thread pool for ASYNC. The benchmark uses tempfile.mkdtemp() with the comment "We can't use tempfile.TemporaryDirectory() due to CheckpointUploadMode.ASYNC".
There was a problem hiding this comment.
Applied your suggestion in 83476f9, including the contrast with SYNC.
| ### What happens when a failure occurs? | ||
|
|
||
| When a failure happens, such as a worker crash or a node preemption, Ray Train restarts with fewer workers. It then tries again to bring the worker group back up to `max_workers`. Without a retry limit, the run exits on the first such failure. To retry the run when worker failures occur, configure {attr}`~ray.train.RunConfig.failure_config` with {attr}`~ray.train.FailureConfig.max_failures`: | ||
| When a failure happens, such as a worker crash or a node preemption, Ray Train restarts with fewer workers. It then tries again to bring the worker group back up to `max_workers`. By default, `max_failures` is 0, so the run exits on the first worker failure. Node preemptions count against a separate budget, `max_preemption_failures`, which retries without a limit by default. To retry the run when worker failures occur, configure {attr}`~ray.train.RunConfig.failure_config` with {attr}`~ray.train.FailureConfig.max_failures`: |
There was a problem hiding this comment.
To note that max preemption failures is very recent addition and should be documented from which version this is true
There was a problem hiding this comment.
max_preemption_failures came in with #64360, first released in Ray 2.58, so the sentence should name that version:
| When a failure happens, such as a worker crash or a node preemption, Ray Train restarts with fewer workers. It then tries again to bring the worker group back up to `max_workers`. By default, `max_failures` is 0, so the run exits on the first worker failure. Node preemptions count against a separate budget, `max_preemption_failures`, which retries without a limit by default. To retry the run when worker failures occur, configure {attr}`~ray.train.RunConfig.failure_config` with {attr}`~ray.train.FailureConfig.max_failures`: | |
| When a failure happens, such as a worker crash or a node preemption, Ray Train restarts with fewer workers. It then tries again to bring the worker group back up to `max_workers`. By default, `max_failures` is 0, so the run exits on the first worker failure. Starting in Ray 2.58, node preemptions count against a separate budget, `max_preemption_failures`, which retries without a limit by default. To retry the run when worker failures occur, configure {attr}`~ray.train.RunConfig.failure_config` with {attr}`~ray.train.FailureConfig.max_failures`: |
83476f9 to
664634d
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
…s, and preemption budget - asynchronous-validation.md: cover both ways the validation run can pass metrics back, note return values need Ray 2.56, and recommend return_value over a placeholder NO_UPLOAD checkpoint. - checkpoints.md: contrast ASYNC with SYNC, where a TemporaryDirectory works because report waits for the upload. - elastic-training.md: scope max_preemption_failures to Ray 2.58 (#64360). Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
664634d to
4be4533
Compare
#66894) ## Why are these changes needed? The Ray Train style-pass PRs, #66886, #66887, and #66888, flagged pre-existing problems in the pages they edited and left them as written, because a style pass shouldn't change claims. This PR fixes the ones that don't change a technical claim. Each fix is settled by the page itself, its own code sample, or its own tables. **Stacked on #66886, #66887, and #66888.** Those three PRs are siblings on `doc-1549-train-vale-style`, #66885's branch, so this PR targets that branch and starts from a merge of all three. Until they merge, the diff here includes their changes. Review only the three commits after the merge commit: - `ea20d30` getting-started guides - `af794c9` overview, framework, and example pages - `67b7b59` user guides Once the style PRs land, I'll rebase onto `master` and retarget there. ### Getting-started guides - Eight numbered lists describe components, parameters, or what a function does, not steps. They're now bullets, as the bot review on #66886 suggested: the three-component lists in the PyTorch, JAX, LightGBM, Transformers, and XGBoost guides, the `prepare_model` and `prepare_data_loader` lists, and the LightGBM `ScalingConfig` parameters. The intro lists that run from "Configure..." to "Launch..." are real sequences and stay numbered. - `getting-started-jax.md`: "PodSlices" is "Pod slices", Google's spelling, in the body and the front-matter description. ### Overview, framework, and example pages - `benchmarks.md`: "perform similarly (within 2.5%)" and "(within 1%)" are false as two-sided bounds. The page's own tables show a 9.5% gap in the PyTorch 16-worker CPU row and 4.3% in the TensorFlow one, both with Ray Train faster. The sentences now say what the tables show: Ray Train is at most 2.5% (PyTorch) and 1% (TensorFlow) slower, and faster in the CPU rows named. - `distributed-tensorflow-keras.md`: "saving model weights but not models" contradicts the sample, which calls `model.save(... "model.keras")` and stores the epoch. The load sample calls `json.dump` without importing `json`, which fails when a reader copies the block alone. - `deepspeed.md`: the `:skipif: True` skeleton used `tokenized_datasets`, `collate_fn`, `num_epochs`, `loss`, and `ray` without defining or importing them, while it defined `train_dataset` and never used it. It now passes `train_dataset` and declares the placeholders the same way it already declares `model = ...`. The runnable versions are literal-included from tested files in `python/ray/train/examples/deepspeed/`. - `examples/lightning/lightning-cola-advanced.ipynb`: "this examples uses" typo, flagged on #66883. The matching "with with" typo in the vicuna notebook isn't fixed here, because #66892 deletes that notebook. ### User guides - `persistent-storage.md`: "In the preceding example, the training loop saves some artifacts to the worker's current working directory." No preceding example does that. - `hyperparameter-optimization.md`: "The next section on fault tolerance describes this further." The next section doesn't cover driver snapshots. The link now points to the driver fault tolerance section of the fault tolerance guide, which does. - `local-mode.md`: the prose said to change only `num_workers`, but the sample's diff also sets `use_gpu=True`. "Master node" stays: the section runs `torchrun` without a Ray cluster, so "head node" would mislead. - `using-accelerators.md`: `get_device` returns one device. - `data-loading-preprocessing.md`: "Ray Data splits all datasets" becomes "Ray Train splits", matching the same page's own statement that Ray Train splits all datasets with `Dataset.streaming_split` by default. Two code comments change to match. Corrections that need Ray Train engineering to confirm are in #66895, stacked on this one. ## Related issue number None. Not a duplicate: I searched open PRs touching `doc/source/train/`. The open PRs there are this stack (#66883, #66885, #66886, #66887, #66888) and the example cleanups (#66892, #66893), which don't touch these lines. ## Checks - Docs-only. The code edits are in a `:skipif: True` skeleton, an untested sample block, and code comments. - `vale` on the changed files from the repo root: alerts only removed, none added. - `codespell` on the changed files: clean. - `doc/.claude/skills/ray-soft-wrap/scripts/softwrap.py --check` on the changed files: clean. - The notebook still parses as JSON. - Full `-W` doc build: relying on the Read the Docs preview. AI assistance (Claude Code) was used to research and draft these edits. Draft until the submitter has reviewed every changed line. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
**Problem**
- Ray Train V2 has been the default since Ray 2.51: `is_v2_enabled()`
defaults to `True`.
- A few Train docs on master still tell readers to set
`RAY_TRAIN_V2_ENABLED=1`.
- The rendered report-callback snippet on the monitoring page asserts
that the variable equals `"1"`. If you copy it as-is, it raises
`KeyError`.
**Change**
- `local-mode.md`: drop `RAY_TRAIN_V2_ENABLED=1` from the two multi-node
`torchrun` commands. The single-node command on the same page already
has none.
- `deprecated.rst`: say that V2 is the default since 2.51, and point to
`RAY_TRAIN_V2_ENABLED=0` for the deprecated V1 API.
- `doc_code/{fault_tolerance,metric_logging,train_tune_interop}.py`:
remove the lines that set or assert the variable.
```
RAY_TRAIN_V2_ENABLED=1 torchrun ... -> torchrun ...
"can be enabled by setting =1" -> "the default starting in Ray 2.51;
for V1, set =0"
os.environ[...] = "1" / assert == "1" -> removed
```
**Decisions to confirm**
- This keeps the "Ray 2.43 through 2.50" notes added in #66895.
- This leaves the intentional `=0` V1 opt-outs alone (`dl_guide.py`,
`tuner.py`, `hvd_trainer.py`, `horovod.md`, the V1 doctests in
`doc/BUILD.bazel`).
**Related:** follows #66895. The FSDP2 example page and several other
templates come from `anyscale/templates` and still set the flag. They
are not part of this PR.
**Tested:** `metric_logging.py` and `train_tune_interop.py` run cleanly
with the variable unset. In `fault_tolerance.py` every section runs up
to the `relax_collectives_on_preemption` block, which needs master
(#66225); the test venv had Ray 2.59.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Why are these changes needed?
The Ray Train style-pass PRs, #66886, #66887, and #66888, flagged pre-existing claims that looked inconsistent with the source and kept them as written. This PR corrects the ones that current source settles. Each claim was already in the docs before the style pass, so none of them is drift that the style pass introduced.
It's stacked on #66894, the mechanical fixes for the same pages, which builds on the three style PRs. The diff against #66894's branch is one commit,
6c6db91.For Ray Train reviewers: these corrections change what the docs say, so please confirm them. Each item cites the source it rests on. Items marked confirm carry a specific point to check.
Getting-started guides
getting-started-jax.md: "By default, this configuration requests one GPU per worker."use_gpudefaults toFalse(python/ray/train/v2/api/config.py). One GPU per worker is whatuse_gpu=Truegives you whenresources_per_workerisn't set (_resources_per_worker_not_noneinpython/ray/air/config.py).getting-started-transformers.md:prepare_trainerdoesn't validate configurations (python/ray/train/huggingface/transformers/_transformers_utils.py). It swaps in Ray Data-aware dataloaders and records a usage tag, so "validate its configurations" goes.getting-started-pytorch-lightning.md: the strategy classes accept their base classes' arguments, but theRayDDPStrategydocstring saysprocess_group_backend,timeout, andstart_methodare disabled and belong inTorchConfig(python/ray/train/lightning/_lightning_utils.py). The sentence now says so.getting-started-pytorch-lightning.md: CI testspytorch-lightning==1.8.6in the Lightning 1.x lane (python/requirements/ml/lightning1.txt,.buildkite/ml.rayci.yml) and2.6.1in the main ML lanes (python/requirements_compiled.txt). Nothing installs 1.6.5 or 2.1.2. The minimum,>=1.6.5, stays as written. Whether to raise it is a separate question for the Train team.User guides
checkpoints.md: Python, not Ray Train, deletes atempfile.TemporaryDirectorywhen itswithblock exits, which can happen before an async upload finishes. Ray Train deletes the local directory only after the upload, whendelete_local_checkpoint_after_uploadis set (_upload_checkpointinpython/ray/train/v2/_internal/execution/context.py). The sentence names the right actor and points out that the page's sample usestempfile.mkdtemp.fault-tolerance.md,hyperparameter-optimization.md, andapi/api.md: Ray Train V2 is the default starting in Ray 2.51.is_v2_enabled()defaultsRAY_TRAIN_V2_ENABLEDtoTrue(python/ray/train/v2/_internal/constants.py) since [train] Turn on Train v2 by default #57857, whichray-2.51.0contains andray-2.50.0doesn't. The intro notes and the "EnableRAY_TRAIN_V2_ENABLED=1" migration steps now scope the variable to Ray 2.43 through 2.50. Whether to drop these notes entirely is a scope decision for the Train team.elastic-training.md: "Without a retry limit, the run exits on the first such failure," where "such failures" includes node preemption.DefaultFailurePolicy(python/ray/train/v2/_internal/execution/failure_handling/default.py) charges preemptions tomax_preemption_failures, which defaults to-1, unlimited (FailureConfiginpython/ray/train/v2/api/config.py). Other worker failures count againstmax_failures, which defaults to 0. The prose and the sample's comment now say so, and the sample's emphasized line moves down one to stay onrun_config. Confirm node loss: a failure counts as a preemption only whenRayActorError.preemptedis set, which needs drain information, so an unannounced node loss should count againstmax_failures.results.md: "Ray Train stores all training results, including reported metrics" contradicts the note at the top of the same page. In V2, the report handler keeps only reports that carry a checkpoint (python/ray/train/v2/_internal/execution/checkpoint/report_handler.py). The sentence now says Ray Train stores checkpoints and the metrics attached to them.asynchronous-validation.md: worker 0's return value is rejected with aValueErrorifcontains_tensor(result)is true (python/ray/train/v2/_internal/execution/worker_group/worker.py). That check inspects nested containers, so "can't contain" is more accurate than "can't be". "Must be Python-based" overstated it. The sentence now suggests converting with.item(), as the page's sample does.Framework pages
huggingface-accelerate.md: "the plan is to deprecateAccelerateTrainerin Ray 2.8" is stale. [Train] Deprecate AccelerateTrainer #40274 deprecated it in 2.8.0, and [Train] Remove Legacy Trainers' code #41276 removed it in 2.9.0. Whether to keep the migration section at all is a scope decision for the Train team.distributed-tensorflow-keras.md:train.reportdoesn't save checkpoint state "on the trainer, where you ran your Python script". Workers copy checkpoint files to the configured storage path (persist_current_checkpointinpython/ray/train/v2/_internal/execution/storage.py, called from_upload_checkpoint). The sentence now says so and links the persistent storage guide.Related issue number
None. Not a duplicate: I searched open PRs touching
doc/source/train/. The open PRs there are this stack and the example cleanups (#66892, #66893), which don't touch these lines.Questions from the style pass that need a Train decision rather than a source check aren't in this PR. Examples are whether Lightning's
AsyncCheckpointIOis incompatible in every upload mode, whether the PyTorch and TensorFlow parity benchmarks should be rerun or retired, and when to drop the V2 opt-in andAccelerateTrainermigration notes. They're tracked separately for Ray Train engineering.Checks
.mdfile underdoc/source/train/, so no library tests run. The one sample edit, a code comment inelastic-training.md, is in an untestedcode-block.valeon the changed files from the repo root: alerts only removed, none added.codespellon the changed files: clean.doc/.claude/skills/ray-soft-wrap/scripts/softwrap.py --checkon the changed files: clean.-Wdoc build: relying on the Read the Docs preview.AI assistance (Claude Code) was used to research and draft these edits. Draft until the submitter has reviewed every changed line and a Ray Train reviewer has confirmed the claims.
🤖 Generated with Claude Code