Skip to content

Fix Unpickler::rebuildTensor storage size check for quantized tensors - #199497

Open
Flamefire wants to merge 13 commits into
pytorch:mainfrom
Flamefire:subbyte-picker-fix
Open

Flamefire wants to merge 13 commits into
pytorch:mainfrom
Flamefire:subbyte-picker-fix

Conversation

@Flamefire

Copy link
Copy Markdown
Collaborator

It currently overestimates the required memory when multiple values are packed into a single byte.

E.g. for quint4x2:

TestQuantizeEagerPTQStatic::test_quantized_embedding_bag - RuntimeError: Tensor: sizes 10 12, strides 12 1, storage offset 0 and itemsize 1 require a storage of at least 120 bytes, but storage only has 60 bytes

This can be reproduced using

  • python test_quantization.py TestQuantizeEagerPTQStatic.test_quantized_embedding
  • python test_quantization.py TestQuantizeEagerPTQStatic.test_quantized_embedding_bag
    and possibly others.

I'm wondering why this isn't caught by CI at all. Only guard seems AVX2 for FBGEMM

It might make sense to fold this calculation into computeStorageNbytes (pass data_type instead of item_size) but that change felt too large and I focused on fixing the immediate bug

@pytorch-bot

pytorch-bot Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

PR Status: ready for maintainer review

Waiting for a maintainer with merge rights for the changed paths to review this PR. Please address any feedback they leave.

✅ AUTOMATED REVIEW - Ready for human review:

The PR fixes the storage-size check in `Unpickler::rebuildTensor` for packed
quantized dtypes `quint4x2` and `quint2x4`; both earlier blocking findings are
fixed and the requested test was added. Recommendation: Approve. Only
non-blocking points remain.

Findings (8):

[minor] torch/csrc/jit/serialization/unpickler.cpp:1047
Non-blocking: zero-element tensors can be wrongly rejected. `size_overflow`
stays set when an earlier dimension product overflows, even if a later dimension
is 0. `computeStorageNbytes` returns 0 as soon as it reaches a zero dimension
(`EmptyTensor.cpp:96-98`), so the merge base accepted these tensors. Example:
`quint4x2` with sizes `[2^63-1, 0, 6]` and strides `[1, 1, 1]` has 0 elements,
but HEAD rejects it because `3 * (2^63-1)` overflows. Fix: skip the sub-byte
branch when `computeStorageNbytes` returned 0.

[minor] torch/csrc/jit/serialization/unpickler.cpp:1067
Non-blocking: the error message is misleading for sub-byte dtypes. It still says
"itemsize 1 require a storage of at least N bytes", but N now includes packing
and row padding. After an overflow, the printed N is the wrapped value. Naming
the dtype or packing factor would help; keep the substring the test matches.

[minor] torch/csrc/jit/serialization/unpickler.cpp:1031
Non-blocking: a comment lost its explanation. It was shortened to "Bound
storage_offset independently". Please restore the reason the check exists:
`computeStorageNbytes` returns 0 for zero-element tensors, so a huge offset
would otherwise get through.

[minor] torch/csrc/jit/serialization/unpickler.cpp:1052
Non-blocking: the sub-byte size rule now differs between call sites. The
unpickler takes the larger of the padded and flat sizes and adds the offset as
whole bytes; `checkInBoundsForStorage` (`Resize.h:101-107`) does a flat
ceil-divide and still divides the offset bytes by the packing factor (line 105);
`get_sub_byte_tensor_size` (`Quantizer.cpp:84-95`) pads rows;
`equal_quantized_cpu` (`QTensor.cpp:266-271`) does a flat ceil-divide. A single
`at::detail` helper, such as the `computeStorageNbytes` dtype overload the PR
description mentions, would keep them consistent. Smaller option for the
padded-row loop at `unpickler.cpp:1042-1051`:
`at::detail::computeStorageNbytesContiguous` (`EmptyTensor.h:50`) does the
product with overflow checks; it throws instead of returning a flag, so the
zero-element skip is needed first.

[minor] aten/src/ATen/EmptyTensor.h:6
Non-blocking: helper placement and includes. `aten/src/ATen/EmptyTensor.h:4-29`
adds an `at::native` block to a header that is otherwise all `at::detail`.
`c10/core/ScalarType.h`, next to the other dtype predicates, would fit better.

[minor] aten/src/ATen/quantized/Quantizer.cpp:85
Non-blocking: `Quantizer.cpp:85` calls `at::native::subByteElementPerByte` but
gets `EmptyTensor.h` only through `ATen/native/TensorFactories.h`. Add a direct
include.

[minor] test/quantization/core/test_quantized_tensor.py:1462
Non-blocking: gaps in `test_jit_serialization_buffer_size`. It only builds 1-D
tensors, so the row-product loop at `unpickler.cpp:1047` never runs; add a 2-D
case with an odd column count: `quint4x2` `[10, 13]` should load with 70 bytes
and be rejected at 69. There is no case with a nonzero `storage_offset`.
`assertEqual` compares bytes that were never written; build `x` from known
values instead, e.g. with `torch.quantize_per_tensor`. Use `subTest` for the
dtype and size loops. Use the public `torch.jit.save` and `torch.jit.load`
instead of `torch.jit._serialization.save/load`.

(1 more not shown, see the review run)

Reviewed commit: d4048dc

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit d4048dc with merge base a53d168 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added release notes: jit release notes category release notes: quantization release notes category labels Oct 2, 2026
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

@Skylion007 Skylion007 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test?

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
pytorchmergebot pushed a commit that referenced this pull request Oct 2, 2026
The Auto PR Triage ownership step still runs on Sonnet 4.6, while the other
Claude triage workflows (claude-issue-triage-run.yml,
claude-distributed-triage.yml) already moved to
`global.anthropic.claude-sonnet-5`. This switches the auto-pr-triage action
to the same model.

Motivation: a recent batch of re-triaged open source PRs (#199461, #199497,
#199513, #199522, #199537) all ended in `bot-triage-error` because the
Sonnet 4.6 ownership run failed. Mostly it quoted diff excerpts that are not
verbatim in the patch, which `validate_ownership.py` rejects. Once it
returned no `structured_output` for `--json-schema`. Other flags (`--effort
low`, `--json-schema`, the turn and budget caps) are supported unchanged on
Sonnet 5.

Test Plan:
The workflow runs on `pull_request_target`, so it executes from the base
branch and this change only takes effect after it lands. The Bedrock model ID
is the one the issue triage workflows already use in production:

```
git grep -n "global.anthropic.claude-sonnet-5" -- .github
```

After landing, re-label a few of the PRs above (remove `bot-triage-error`,
then remove and re-add `open source`) and check the Auto PR Triage runs.

This PR was authored with the help of an AI assistant (Claude Code).
Pull Request resolved: #199570
Approved by: https://github.com/janeyx99
@Flamefire
Flamefire requested a review from jerryzh168 as a code owner October 5, 2026 10:48
@soulitzer
soulitzer requested review from andrewor14 and vkuzo October 9, 2026 01:05
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Oct 9, 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
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…99570)

The Auto PR Triage ownership step still runs on Sonnet 4.6, while the other
Claude triage workflows (claude-issue-triage-run.yml,
claude-distributed-triage.yml) already moved to
`global.anthropic.claude-sonnet-5`. This switches the auto-pr-triage action
to the same model.

Motivation: a recent batch of re-triaged open source PRs (pytorch#199461, pytorch#199497,
pytorch#199513, pytorch#199522, pytorch#199537) all ended in `bot-triage-error` because the
Sonnet 4.6 ownership run failed. Mostly it quoted diff excerpts that are not
verbatim in the patch, which `validate_ownership.py` rejects. Once it
returned no `structured_output` for `--json-schema`. Other flags (`--effort
low`, `--json-schema`, the turn and budget caps) are supported unchanged on
Sonnet 5.

Test Plan:
The workflow runs on `pull_request_target`, so it executes from the base
branch and this change only takes effect after it lands. The Bedrock model ID
is the one the issue triage workflows already use in production:

```
git grep -n "global.anthropic.claude-sonnet-5" -- .github
```

After landing, re-label a few of the PRs above (remove `bot-triage-error`,
then remove and re-add `open source`) and check the Auto PR Triage runs.

This PR was authored with the help of an AI assistant (Claude Code).
Pull Request resolved: pytorch#199570
Approved by: https://github.com/janeyx99
github-actions[bot]

This comment was marked as outdated.

Avoid breaking backwards compatibility.
For large nbytes (e.g. INT64_MAX-1) `a + b - 1` may overflow.
github-actions[bot]

This comment was marked as outdated.

github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed stale reviews from themself November 21, 2026 10:38

Withdrawn: the automated review of 8a6e7d5 found nothing blocking.

Values with different sign would be wrong: `ceil_div_safe(-3, 2) -> 0` instead of `-1`

Usually inputs are size_t/uint64_t anyway, so this isn't too constrained and can be relaxed as required

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review of d4048dc: nothing blocking; ready for human review.

The PR fixes the storage-size check in Unpickler::rebuildTensor for packed quantized dtypes quint4x2 and quint2x4; both earlier blocking findings are fixed and the requested test was added. Recommendation: Approve. Only non-blocking points remain.

⚪ 8 non-blocking findings

for (const auto s : c10::IntArrayRef(size).slice(0, size.size() - 1)) {

Non-blocking: zero-element tensors can be wrongly rejected. size_overflow stays set when an earlier dimension product overflows, even if a later dimension is 0. computeStorageNbytes returns 0 as soon as it reaches a zero dimension (EmptyTensor.cpp:96-98), so the merge base accepted these tensors. Example: quint4x2 with sizes \[2^63-1, 0, 6\] and strides \[1, 1, 1\] has 0 elements, but HEAD rejects it because 3 * (2^63-1) overflows. Fix: skip the sub-byte branch when computeStorageNbytes returned 0.


Non-blocking: the error message is misleading for sub-byte dtypes. It still says "itemsize 1 require a storage of at least N bytes", but N now includes packing and row padding. After an overflow, the printed N is the wrapped value. Naming the dtype or packing factor would help; keep the substring the test matches.


// Bound storage_offset independently

Non-blocking: a comment lost its explanation. It was shortened to "Bound storage_offset independently". Please restore the reason the check exists: computeStorageNbytes returns 0 for zero-element tensors, so a huge offset would otherwise get through.


required_nbytes = std::max(padded_nbytes, flat_nbytes);

Non-blocking: the sub-byte size rule now differs between call sites. The unpickler takes the larger of the padded and flat sizes and adds the offset as whole bytes; checkInBoundsForStorage (Resize.h:101-107) does a flat ceil-divide and still divides the offset bytes by the packing factor (line 105); get_sub_byte_tensor_size (Quantizer.cpp:84-95) pads rows; equal_quantized_cpu (QTensor.cpp:266-271) does a flat ceil-divide. A single at::detail helper, such as the computeStorageNbytes dtype overload the PR description mentions, would keep them consistent. Smaller option for the padded-row loop at unpickler.cpp:1042-1051: at::detail::computeStorageNbytesContiguous (EmptyTensor.h:50) does the product with overflow checks; it throws instead of returning a flag, so the zero-element skip is needed first.


namespace native {

Non-blocking: helper placement and includes. aten/src/ATen/EmptyTensor.h:4-29 adds an at::native block to a header that is otherwise all at::detail. c10/core/ScalarType.h, next to the other dtype predicates, would fit better.


const int64_t element_per_byte = at::native::subByteElementPerByte(t);

Non-blocking: Quantizer.cpp:85 calls at::native::subByteElementPerByte but gets EmptyTensor.h only through ATen/native/TensorFactories.h. Add a direct include.


def test_jit_serialization_buffer_size(self):

Non-blocking: gaps in test_jit_serialization_buffer_size. It only builds 1-D tensors, so the row-product loop at unpickler.cpp:1047 never runs; add a 2-D case with an odd column count: quint4x2 \[10, 13\] should load with 70 bytes and be rejected at 69. There is no case with a nonzero storage_offset. assertEqual compares bytes that were never written; build x from known values instead, e.g. with torch.quantize_per_tensor. Use subTest for the dtype and size loops. Use the public torch.jit.save and torch.jit.load instead of torch.jit._serialization.save/load.


required_nbytes = std::max(padded_nbytes, flat_nbytes);

Non-blocking: some sub-byte views that used to load are now rejected. The padded-row rule treats size.back() as the packed row whatever the strides are, so zero-stride and overlapping-stride views that the merge base accepted are now rejected. Example: quint4x2 \[100\] with stride \[0\] on a 1-byte storage needed 1 byte and now needs 50. Python torch.load goes through set_ and checkInBoundsForStorage, which uses only the flat bound, so the two loaders now disagree. Rejecting these is probably the right trade-off, because int_repr and prepack read the padded extent. Please say so in the PR description or release note.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

This branch was previously deployed

1 inactive (outdated) deployment
bedrock — 8bde1cdf Deployed Oct 2, 2026 by soulitzer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: jit release notes category release notes: quantization release notes category 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.

5 participants