Skip to content

Tests + CI guard: batched left-padded generation can never silently regress again (#1066, #3699) - #6145

Merged
danielhanchen merged 7 commits into
mainfrom
tests/leftpad-generation-guard
Jun 10, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
tests/leftpad-generation-guard

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

Why

Batched left-padded generation has been broken twice without anything catching it. Bisecting the history:

Event Commit / PR Date What happened
Bug introduced cc4c5d7 (#709, Gemma2) Jul 2024 _fast_prepare_inputs_for_generation shipped with position_ids = cache_position (counts left-pad tokens) and a 2D attention mask truncated to its last column
Reported #1066 Sep 2024 Short prompts batched with long ones produce gibberish
Partial fix 332eabf (#2216) Jun 2025 Mask truncation fixed; the position_ids bug stayed latent
Reported again #3699 Dec 2025 Padded rows generate garbage in cached decode
Full fix 6d0f864 (#4100) Feb 2026 Per-row position_ids derived from attention_mask.cumsum(-1) - 1

The shared function covers llama, qwen2, qwen3, qwen3_moe, mistral, gemma, gemma2, cohere and granite via fix_prepare_inputs_for_generation, and until now had zero test coverage.

What this adds

No new workflow and no new CI job. One HARD GATE step inside the existing Core workflow (consolidated-tests-ci.yml), placed right after the callback signature drift detector where the CPU torch stack is already installed, running a single test file:

  • tests/utils/test_prepare_inputs_leftpad.py with two layers:
    1. AST structural checks using only the stdlib ast module (no unsloth import, no torch beyond the module import): the cumsum-from-mask branch exists, cache_position is only ever a fallback for position_ids, the 2D mask is never truncated to its last column, and the model families above stay wired via fix_prepare_inputs_for_generation. These keep working even when the package fails to import, because unsloth is only imported lazily inside the behavioral tests.
    2. Behavioral checks calling the real function with synthetic left-padded masks, fake DynamicCache / legacy tuple caches and a recording 4D-mask builder. Exact expected position_ids for prefill and cached decode (the row with 2 pads must get position 2, not cache_position 4). Runs through the existing tests/conftest.py CUDA spoof, fully deterministic on GPU-less runners.
  • tests/utils/test_batched_leftpad_generation_gpu.py: manual end-to-end check, auto-skipped without CUDA, not referenced by CI.

Validation

  • Current main: all 11 assertions pass. Pre-Fix/pr 3699 leftpad prefill main #4100 (6d0f8643~1): 8 fail. Pre-Fix batched generation for prompts of different lengths #2216 (332eabf3~1): fails as well, including the mask-truncation asserts. So the guard demonstrably catches both historical incarnations at the commit boundary where each was fixed.
  • Staging proof on GPU-less hosted runners (danielhanchen/unsloth-staging-2): standalone-workflow round was PR 170 green / PR 171 red in seconds at the AST layer; consolidated-CI round is PR 170 (updated, green expected) / PR 172 (red expected at the HARD GATE step in every Core matrix combo).
  • Also verified end to end on GPUs separately: Llama-3.1-8B, Llama-3.2-1B, gemma-3-4b-it and mistral-7b-v0.3, bf16 and 4-bit, exact solo-vs-batched token matches.

Note: the unsloth_zoo full-pytest step fails on the staging fork for the HF=latest and HF=default combos on clean code too; that is a pre-existing zoo-vs-latest-transformers breakage unrelated to this PR (the pinned HF=4.57.6 combo is green).

danielhanchen and others added 2 commits June 10, 2026 12:37
Three layers of tests plus a path-filtered CI workflow so the left-padding
position_ids / attention-mask bug class cannot silently return:

- tests/utils/test_prepare_inputs_ast_guard.py: import-free AST checks on
  _fast_prepare_inputs_for_generation (cumsum-from-mask branch present,
  cache_position only as fallback, no mask truncation, model families wired)
- tests/utils/test_prepare_inputs_leftpad.py: CPU behavioral unit test with
  synthetic left-padded masks and fake caches; exact expected position_ids
  for prefill and cached decode
- tests/utils/test_batched_leftpad_generation_gpu.py: optional GPU e2e,
  solo vs batched prefix match, skipped without CUDA
- .github/workflows/batch-inference-guard.yml: ubuntu-latest CPU job running
  the two deterministic layers on PRs touching unsloth/models/**

Validated: all pass on main; both CPU layers fail at 6d0f864~1 (pre #4100)
and at 332eabf~1 (pre #2216), reproducing the historical bug signatures.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces comprehensive regression and structural guards for batched left-padded generation, including end-to-end GPU tests, CPU-based behavioral tests, and an AST-based structural guard. The review feedback provides valuable improvements to ensure the AST parser is fully compatible with Python 3.8 (addressing differences in how slices, indexes, and unparsing are handled) and recommends specifying UTF-8 encoding when reading files to prevent decoding issues on Windows platforms.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +44 to +52
def _load_function():
tree = ast.parse(LLAMA_PY.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == FUNC_NAME:
return node
raise AssertionError(
f"{FUNC_NAME} not found in {LLAMA_PY}; if it was renamed or moved, "
"update this guard so batched left-padded generation stays protected"
)

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.

medium

To prevent UnicodeDecodeError on platforms where the default system encoding is not UTF-8 (such as Windows), specify encoding="utf-8" when reading the file. Additionally, we define helper functions to ensure full compatibility with Python 3.8 AST differences.

def _unparse(node):
    if hasattr(ast, "unparse"):
        return ast.unparse(node)
    return ast.dump(node)


def _get_index_node(slice_node):
    if hasattr(ast, "Index") and isinstance(slice_node, ast.Index):
        return slice_node.value
    return slice_node


def _get_slice_elements(slice_node):
    if isinstance(slice_node, ast.Tuple):
        return slice_node.elts
    if hasattr(ast, "ExtSlice") and isinstance(slice_node, ast.ExtSlice):
        parts = []
        for dim in slice_node.dims:
            if hasattr(ast, "Index") and isinstance(dim, ast.Index):
                parts.append(dim.value)
            else:
                parts.append(dim)
        return parts
    return [slice_node]


def _load_function():
    tree = ast.parse(LLAMA_PY.read_text(encoding="utf-8"))
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == FUNC_NAME:
            return node
    raise AssertionError(
        f"{FUNC_NAME} not found in {LLAMA_PY}; if it was renamed or moved, "
        "update this guard so batched left-padded generation stays protected"
    )

Comment on lines +72 to +79
def _is_kwargs_position_ids_target(target):
return (
isinstance(target, ast.Subscript)
and isinstance(target.value, ast.Name)
and target.value.id == "kwargs"
and isinstance(target.slice, ast.Constant)
and target.slice.value == "position_ids"
)

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.

medium

On Python 3.8, subscript slices are wrapped in an ast.Index node (e.g., Index(value=Constant(value="position_ids"))). To ensure the AST guard is fully compatible with Python 3.8 and doesn't silently fail to detect kwargs["position_ids"] targets, use the _get_index_node helper to extract the underlying constant.

def _is_kwargs_position_ids_target(target):
    if not isinstance(target, ast.Subscript):
        return False
    if not (isinstance(target.value, ast.Name) and target.value.id == "kwargs"):
        return False
    idx_node = _get_index_node(target.slice)
    return isinstance(idx_node, ast.Constant) and idx_node.value == "position_ids"

Comment on lines +111 to +124
assert "cumsum" in body_names and _mentions_attention_mask(
ast.Module(body = branch.body, type_ignores = [])
), (
"the attention-mask branch must compute position_ids via "
"attention_mask.cumsum(...); reintroducing cache_position-based "
"positions breaks left-padded batched generation (issue #3699)"
)
assert "masked_fill_" in body_names or "masked_fill" in body_names, (
"the attention-mask branch must mask pad positions (masked_fill on mask == 0)"
)
assigns_kwargs = any(
isinstance(stmt, ast.Assign)
and any(_is_kwargs_position_ids_target(t) for t in stmt.targets)
for stmt in ast.walk(ast.Module(body = branch.body, type_ignores = []))

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.

medium

Avoid constructing dummy ast.Module objects to check for attention mask mentions and keyword assignments, as this can have subtle compatibility issues across Python versions. Instead, iterate over and walk the statements in branch.body directly.

    assert "cumsum" in body_names and any(_mentions_attention_mask(stmt) for stmt in branch.body), (
        "the attention-mask branch must compute position_ids via "
        "attention_mask.cumsum(...); reintroducing cache_position-based "
        "positions breaks left-padded batched generation (issue #3699)"
    )
    assert "masked_fill_" in body_names or "masked_fill" in body_names, (
        "the attention-mask branch must mask pad positions "
        "(masked_fill on mask == 0)"
    )
    assigns_kwargs = any(
        isinstance(sub, ast.Assign)
        and any(_is_kwargs_position_ids_target(t) for t in sub.targets)
        for stmt in branch.body
        for sub in ast.walk(stmt)
    )

)
if derives_from_cache_position and id(node) not in orelse_nodes:
offenders.append(ast.unparse(node))

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.

medium

Use the _unparse helper to support Python 3.8, where ast.unparse is not available.

Suggested change
offenders.append(_unparse(node))

Comment on lines +177 to +194
if isinstance(sl, ast.Tuple) and len(sl.elts) == 2:
col = sl.elts[1]
is_last_col_list = (
isinstance(col, ast.List)
and len(col.elts) == 1
and isinstance(col.elts[0], ast.UnaryOp)
)
is_last_col_slice = (
isinstance(col, ast.Slice)
and col.lower is not None
and isinstance(col.lower, ast.UnaryOp)
and getattr(getattr(col.lower, "operand", None), "value", None) == 1
and col.upper is None
)
if is_last_col_list or is_last_col_slice:
offenders.append(ast.unparse(node))
assert not offenders, (
"the 2D attention mask must not be truncated to its last column; this "

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.

medium

On Python 3.8, multi-dimensional subscript slices are represented as ast.ExtSlice rather than ast.Tuple. Use the _get_slice_elements helper to normalize the slice elements and ensure compatibility across Python 3.8 and 3.9+.

        # Match a trailing [-1]-style column selection: [:, [-1]] or [:, -1:]
        sl = value.slice
        elements = _get_slice_elements(sl)
        if len(elements) == 2:
            col = elements[1]
            is_last_col_list = (
                isinstance(col, ast.List)
                and len(col.elts) == 1
                and isinstance(col.elts[0], ast.UnaryOp)
            )
            is_last_col_slice = (
                isinstance(col, ast.Slice)
                and col.lower is not None
                and isinstance(col.lower, ast.UnaryOp)
                and getattr(getattr(col.lower, "operand", None), "value", None) == 1
                and col.upper is None
            )
            if is_last_col_list or is_last_col_slice:
                offenders.append(_unparse(node))

if not path.exists():
continue
if "fix_prepare_inputs_for_generation(" not in path.read_text():
missing.append(fname)

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.

medium

Specify encoding="utf-8" when reading the model files to prevent potential UnicodeDecodeError on non-UTF-8 default platforms.

Suggested change
missing.append(fname)
if "fix_prepare_inputs_for_generation(" not in path.read_text(encoding="utf-8"):

@danielhanchen

Copy link
Copy Markdown
Member Author

Staging proof on GPU-less hosted runners (danielhanchen/unsloth-staging-2, following the studio-load-orchestrator convention):

Staging PRs: danielhanchen#170 (green) and danielhanchen#171 (red, draft, never to be merged).

The CI path is fully deterministic with no GPU anywhere: layer 1 is stdlib-only AST checks, layer 2 is a CPU unit test of the real function. The GPU end-to-end file self-skips without CUDA and is for manual runs only.

danielhanchen and others added 5 commits June 10, 2026 12:48
…oral tests

No new workflow and no new CI job: the guard now runs as one HARD GATE step
inside consolidated-tests-ci.yml, right after the callback signature drift
detector, where the CPU torch stack is already installed. The AST structural
checks and the behavioral unit tests live in a single file
(tests/utils/test_prepare_inputs_leftpad.py); the AST layer stays stdlib-only
with unsloth imported lazily inside the behavioral tests, so import breakage
cannot mask the structural checks.

Revalidated after the merge: 11 assertions pass on main, 8 fail at
6d0f864~1 (pre #4100).
@danielhanchen

Copy link
Copy Markdown
Member Author

Restructured per review: no standalone workflow anymore. The guard is now a single HARD GATE step in consolidated-tests-ci.yml (after the callback signature drift detector, where the CPU stack is already installed), and the AST + behavioral layers live in one file, tests/utils/test_prepare_inputs_leftpad.py. Zero new CI jobs.

Staging proof for the consolidated structure (danielhanchen/unsloth-staging-2):

The job-level failures visible on the green run are the pre-existing unsloth_zoo full-pytest breakage against HF latest/default combos, which fails on clean code without this PR as well; the pinned HF=4.57.6 combo is fully green.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant