Skip to content

[DCP] Keep quantized HF scale file paths inside the checkpoint directory - #199436

Closed
bhaskargurram-ai wants to merge 1 commit into
pytorch:mainfrom
bhaskargurram-ai:fix/quantized-hf-storage-path-traversal
Closed

bhaskargurram-ai wants to merge 1 commit into
pytorch:mainfrom
bhaskargurram-ai:fix/quantized-hf-storage-path-traversal

Conversation

@bhaskargurram-ai

Copy link
Copy Markdown

Before submitting, please review:

Go through the following checklist

  • Passes lint (spin fixlint)
  • Added/updated tests
  • Updated documentation (if applicable)
  • Included benchmark results (for PRs impacting perf)

Issue being fixed

Fixes #199028

BC-breaking?

No. Checkpoints whose weight_map entries are relative paths inside the checkpoint directory (including subdirectories and Hugging Face cache snapshots, whose files are symlinks into ../../blobs) load exactly as before. Only entries that are absolute or contain .. now raise ValueError.

Summary (human written only)

Hardening for QuantizedHuggingFaceStorageReader, as described in #199028. When a scale tensor lives in a different file from its weight, the reader opened Path(self.path) / scale_file_name with scale_file_name taken straight from model.safetensors.index.json. An absolute entry replaces the checkpoint directory and ../ walks out of it, so the index could make the reader load scales from any safetensors file the process can read. SECURITY.md treats checkpoints as trusted input, so this is defense in depth rather than a vulnerability fix.

The new _get_checkpoint_file_path() helper rejects entries that have an anchor (absolute paths, including Windows drives) or a .. component, then joins them to the checkpoint directory as before. I kept the check lexical rather than using the resolve() + is_relative_to() check suggested in the issue: in a huggingface_hub cache snapshot, every file is a symlink to ../../blobs/<hash>. A resolve()-based check would reject every cross-file scale lookup in a normal snapshot_download directory. The base HuggingFaceStorageReader also already follows symlinks for the files it finds in the checkpoint directory.

Tests added to test/distributed/checkpoint/test_quantized_hf_storage.py:

  • test_scale_file_in_subdirectory: a nested relative entry (shards/model-00002-of-00002.safetensors) is still opened from the checkpoint directory and dequantized.
  • test_scale_file_parent_traversal_rejected: ../secret.safetensors and shards/../../secret.safetensors raise ValueError, and nothing is opened.
  • test_scale_file_absolute_path_rejected: an absolute path to a file next to the checkpoint raises ValueError, and nothing is opened.

How I tested it: I copied the patched quantized_hf_storage.py over a torch==2.14.1+cpu wheel install (Python 3.12), then ran the test file with pytest from outside the repo: 5 passed, 2 subtests passed. With the original file, the three new rejection cases fail (ValueError not raised) and the subdirectory test passes. I also ran an end-to-end check with real safetensors files and dcp.load(..., no_dist=True). Before the fix, an absolute or ../ index entry loaded the scale from secret.safetensors. After the fix, both are rejected, and both a plain checkpoint and an HF-cache-style symlinked checkpoint still load correctly. ruff check, ruff format --check (0.14.4, as pinned in tools/linter/adapters), usort check and flake8 (with the pinned plugins) are clean on the changed files.

QuantizedHuggingFaceStorageReader opened a scale tensor stored in a
different file with Path(self.path) / scale_file_name, where
scale_file_name comes straight from the weight_map in
model.safetensors.index.json. An absolute path replaces the checkpoint
directory and "../" components walk out of it, so an index could make
the reader load scales from any safetensors file the process can read.

Add _get_checkpoint_file_path(), which rejects absolute paths (any path
with an anchor, including Windows drives) and paths with ".." components
with a ValueError before joining them to the checkpoint directory. The
check is lexical on purpose: Hugging Face cache snapshots store their
files as symlinks into a sibling blobs directory, so a resolve()-based
containment check would reject valid cached checkpoints. Valid relative
entries, including subdirectories, are opened exactly as before.

Fixes pytorch#199028

Test Plan:

```
python test/distributed/checkpoint/test_quantized_hf_storage.py
```
@pytorch-bot

pytorch-bot Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

PR Status: missing actionable issue

Auto PR Triage did not find either of the following when it checked this PR:

  • a linked issue labeled actionable (Fixes #<issue> or Part of #<issue>); or
  • a maintainer named in the description who agreed to the change (Supported by @<maintainer>).

Such PRs are a low priority for maintainers to review and might not get a response given the very high volume of PRs we receive. Please focus on actionable issues to ensure a maintainer will be available to review your PR.

If one of these applies, add the matching line to the PR description. If there is no actionable issue for this change yet, you can open one (or comment on an existing one) and wait for a maintainer to label it actionable. Adding actionable to an already-linked issue automatically requests re-triage of open, non-draft PRs with open source and missing actionable issue, unless automated triage is disabled. Adding a valid actionable-issue link or Supported by line to the description also requests re-triage automatically. Marking the PR ready, reopening it, or re-enabling automated triage rechecks existing links and support. If re-triage is still needed, comment @pytorchbot triage to run Auto PR Triage again.

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/199436

Note: Links to docs will display an error until the docs builds have been completed.

⚠️ 5 Awaiting Approval

As of commit 83ed4e4 with merge base e95ed7c (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: bhaskargurram-ai / name: Bhaskar Gurram (83ed4e4)

@pytorch-bot

pytorch-bot Bot commented Oct 2, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@bhaskargurram-ai

Copy link
Copy Markdown
Author

cc @malfet since you filed #199028. One choice to flag: the check is lexical (rejects absolute paths and ..) rather than resolve()-based, because HF cache snapshots are symlinks into ../../blobs. The details are in the summary. Happy to change it if you'd prefer a different approach.

soulitzer added a commit that referenced this pull request Oct 2, 2026
The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines
inside an excerpt (#197857, #199447, #199471, #199472, #199497). Two turned an
unchanged context line, which also appeared in the `@@` hunk header, into a
fake `-`/`+` pair (#199453, #199461). The worker prompt now says to keep
excerpts short by choosing a shorter run of adjacent lines, never by skipping
or cutting lines, and never to turn unchanged lines or hunk-header text into
changed lines. The validator stays strict: a mismatched excerpt can't be told
apart from an invented one, and a failed run falls back to human triage. The
replay below shows the wording fixes the hunk-header pattern but only partly
helps the other two, so a structural follow-up is still needed.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of three failed runs:
each run's patch at its analyzed head_sha and CODEOWNERS at its workflow_sha.
Outputs were checked with validate_result. Evidence-excerpt failures:

| PR (pattern)                         | old worker.md | new worker.md |
|--------------------------------------|---------------|---------------|
| #199461 (fake -/+ from hunk header)  | 2/3           | 0/3           |
| #197857 (skipped comment lines)      | 4/4           | 2/3           |
| #199425 (cut a long comment line)    | 2/5           | 3/5           |

The remaining failures still drop two comment lines from the middle of an
excerpt (#197857) or stop a long comment line at the end of a sentence
(#199425).

This PR was authored with an AI assistant (Claude Code).

ghstack-source-id: d937117
Pull-Request-resolved: #199428
soulitzer added a commit that referenced this pull request Oct 2, 2026
The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines inside an excerpt
(#197857, #199447, #199471, #199472, #199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (#199453,
#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (#199453, #199461), and the one replay failure
(#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

This PR was authored with an AI assistant (Claude Code).

ghstack-source-id: 546c754
Pull-Request-resolved: #199428
pytorchmergebot pushed a commit that referenced this pull request Oct 2, 2026
…99428)

The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines inside an excerpt
(#197857, #199447, #199471, #199472, #199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (#199453,
#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (#199453, #199461), and the one replay failure
(#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

This PR was authored with an AI assistant (Claude Code).
Pull Request resolved: #199428
Approved by: https://github.com/janeyx99
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot missing actionable issue A PR without a linked actionable issue or maintainer sponsor triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 2, 2026
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…torch#199428)

The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (pytorch#199436, pytorch#199440, pytorch#199463, pytorch#199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, pytorch#199425). Five skipped lines inside an excerpt
(pytorch#197857, pytorch#199447, pytorch#199471, pytorch#199472, pytorch#199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (pytorch#199453,
pytorch#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (pytorch#199453, pytorch#199461), and the one replay failure
(pytorch#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

This PR was authored with an AI assistant (Claude Code).
Pull Request resolved: pytorch#199428
Approved by: https://github.com/janeyx99
@soulitzer soulitzer added missing actionable issue A PR without a linked actionable issue or maintainer sponsor and removed missing actionable issue A PR without a linked actionable issue or maintainer sponsor labels Oct 15, 2026
@bhaskargurram-ai

Copy link
Copy Markdown
Author

Closing this since it has been idle for a while and I don't plan to follow up on it. Thanks!

This branch was previously deployed

1 inactive deployment
bedrock — 83ed4e40 Deployed Oct 2, 2026 by janeyx99
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/torchtitan Run TorchTitan integration tests missing actionable issue A PR without a linked actionable issue or maintainer sponsor open source release notes: distributed (checkpoint) triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Validate scale file paths in quantized HuggingFace checkpoint indexes

4 participants