Repository navigation
Tests + CI guard: batched left-padded generation can never silently regress again (#1066, #3699) - #6145
Conversation
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.
There was a problem hiding this comment.
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.
| 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" | ||
| ) |
There was a problem hiding this comment.
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"
)| 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" | ||
| ) |
There was a problem hiding this comment.
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"| 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 = [])) |
There was a problem hiding this comment.
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)) | ||
|
|
| 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 " |
There was a problem hiding this comment.
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) |
|
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. |
…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).
|
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. |
Why
Batched left-padded generation has been broken twice without anything catching it. Bisecting the history:
_fast_prepare_inputs_for_generationshipped withposition_ids = cache_position(counts left-pad tokens) and a 2D attention mask truncated to its last columnattention_mask.cumsum(-1) - 1The 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.pywith two layers:astmodule (no unsloth import, no torch beyond the module import): the cumsum-from-mask branch exists,cache_positionis only ever a fallback forposition_ids, the 2D mask is never truncated to its last column, and the model families above stay wired viafix_prepare_inputs_for_generation. These keep working even when the package fails to import, because unsloth is only imported lazily inside the behavioral tests.tests/conftest.pyCUDA 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
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.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).