Skip to content

Accept list, tuple and non-default-index Series groups in group splits - #1665

Open
Sohail Shaikh (sohailshk) wants to merge 19 commits into
microsoft:mainfrom
sohailshk:fix/group-split-groups-indexing
Open

Sohail Shaikh (sohailshk) wants to merge 19 commits into
microsoft:mainfrom
sohailshk:fix/group-split-groups-indexing

Conversation

@sohailshk

Copy link
Copy Markdown

Why are these changes needed?

groups is documented as "None or array-like", but split_type="group" indexes the labels positionally. Realistic repro (iris, train_test_split(X, y, df["cluster"]) which keeps the Series index, regression, split_type="group", eval_method="holdout"): KeyError: "None of [Index([9, 11, ...])] are in the [index]" on main; it runs on this branch (the cv variant already worked).
Other cases on main (each run): a list or tuple raises TypeError: only integer scalar arrays can be converted to a scalar index (holdout) or AttributeError: ... no attribute 'iloc' (cv, also with split_type=GroupKFold(3)). A Series whose index is a permutation of 0..n-1 raises nothing, but the holdout split stores other rows' labels in state.groups / state.groups_val (checked at state level; the effect on ranking metrics is from code reading only).
The change converts list, tuple and Series group labels (and groups_val) to an ndarray when the data is prepared. New tests: list, tuple, offset-index Series (holdout and cv), GroupKFold with a list (cv), and the permuted-index state check; 7 fail on main, all pass here. Existing test_split tests pass except two that import catboost (not installed).

Related issue number

Related: #1384/#1385, #1396/#1405, #1586 (same indexing, sample_weight side).

Checks

Checks run: black (line length 120) and ruff on the changed files. The pinned pre-commit hook versions were not run. No doc changes are needed.

AutoML.fit(split_type='group') indexed the group labels positionally with
groups[train_idx]. A list or tuple raised TypeError (holdout) or AttributeError
(cv, no .iloc), and a pd.Series with a non-default index raised KeyError in the
holdout split because it was indexed by label. Convert such group labels to an
ndarray when the data is prepared.

Copilot AI 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.

🟢 Approval recommended

No active review issues are reported for the group-label positional-indexing fix.

No open issues 🎉

What changed in this PR

This PR fixes positional indexing of array-like group labels in FLAML’s group-based splits, extending earlier fixes for target and sample-weight alignment.

Changes:

  • Normalize list, tuple, and pandas Series values for groups and groups_val to NumPy arrays.
  • Add regression tests for holdout and cross-validation splits, custom GroupKFold, and label alignment with permuted Series indexes.
File Description
test/​automl/​test_split.py Adds coverage for supported group containers and positional label alignment.
flaml/​automl/​task/​generic_task.py Normalizes group labels during data validation for positional indexing.

Review effort: Balanced

@thinkall Li Jiang (thinkall) 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.

Overall review of the complete patch at 1c6d739579d67873b1fa29a82e0ec29fcc09e884: the six independent Medium review-code lenses completed using gemini-4-carbon at high reasoning, with unresolved test-evidence follow-ups retained.

Please cover caller-supplied X_val/y_val/non-array groups_val, and check the labels passed to each CV fold rather than only the rows seen by RandomForestClassifier.fit. Also assert that at least one captured fit actually holds out groups: set(counts) <= {0, 10} accepts full-data fits and does not establish that on its own.

The added regression tests give 8 passed, 1 skipped on each native Python 3.10 and 3.13 stack; identical definitions on exact main give 7 failed, 1 passed, 1 skipped. This verifies the stated list/tuple/Series fixes, not a complete Spark or optional-dependency matrix. I also checked the broader pd.Index concern: it fails identically on this head and main, and is outside the explicitly stated container fix, so I am not reporting it as a new regression or requiring unrelated broadening here.

The original six reviewer outcomes and this scope adjudication are retained in local artifact-only evidence commits. No clean overall signoff or PR approval is submitted while the focused test requests remain; no foreign thread was resolved or prior review dismissed.

Posted by thinkall-agent-auto-reviewer

Spy on the labels and rows handed to each evaluated fold, cover X_val/y_val with non-array groups and groups_val, and assert that at least one fit holds groups out.
@sohailshk

Copy link
Copy Markdown
Author

Thanks for the review, thinkall. I've added the requested test coverage and pushed the changes in commit d4cf7a5b.

  1. Caller-supplied validation data
    Added tests covering caller-supplied X_val and y_val with non-array groups_val inputs, including:
  • Lists
  • Tuples
  • Pandas Series with offset indices

This ensures that validation groups are handled correctly across different input types and index configurations.
2. Per-fold group validation
Added per-fold assertions covering both the holdout and cross-validation paths.
For each fold, the tests verify that:

  • groups matches the group labels corresponding to the training rows.
  • groups_val matches the group labels corresponding to the validation rows.
  • Training and validation group sets do not overlap.

Also added an explicit assertion that at least one captured fit actually holds out groups. This ensures the tests verify genuine group separation rather than passing without exercising the intended behavior.
3. Regression verification
The new per-fold tests fail in 4 of 9 cases when generic_task.py is reverted to the version on main.
This confirms that the tests detect the behavior addressed by the existing source change rather than simply validating the expected output on the current implementation.
4. Scope of this commit
Commit d4cf7a5b contains test changes only. No source code has been modified in this commit.
5. Test results

  • Group-related tests: 21 passed.
  • Two other tests fail with ModuleNotFoundError because optional dependencies are missing in the current environment.

These dependency-related failures are unrelated to this change.
Summary
The additional coverage verifies caller-supplied validation data, non-array group inputs, and per-fold group isolation across both holdout and CV paths.
The regression checks also confirm that the new tests catch failures when the relevant source implementation is reverted to main.

Copilot AI 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.

🟢 Approval recommended

No active review issues are reported for the group-label normalization change.

No open issues 🎉

Review effort: Balanced

@thinkall Li Jiang (thinkall) 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.

The selected group-split regressions produce 17 passes and one existing skip on each native stack, on both current and preceding production source. The new row-alignment and nonvacuity checks improve test evidence.

Remaining test-quality follow-ups: require captured training groups to be present before comparing them; for three-fold CV, verify three nonoverlapping validation sets covering the rows rather than accepting any one held-out fold; and exercise positional indexing directly on captured caller-supplied groups_val instead of normalizing it inside the assertion.

These are assertion gaps, not newly demonstrated production row misalignment. This Low test-delta review does not supersede the retained full Medium scope or grant whole-PR approval.

Posted by thinkall-agent-auto-reviewer

@sohailshk

Copy link
Copy Markdown
Author

Implemented all three requested changes:

  • Require captured training groups to be present.
  • Verify that 3-fold CV produces three disjoint validation sets covering all rows.
  • Test positional indexing using the caller's groups_val.

The new CV test fails on main only for the list case. Both Series cases already pass because CV uses positional indexing.
Tests: test_split.py: 28 passed, 2 failed. The two failures require CatBoost and MinIO, which are not installed. Results are the same with NumPy 2.5.5 and 1.26.4.

Copilot AI 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.

🟢 Approval recommended

No active review issues block approval of the expanded group-label input support.

No open issues 🎉

Review effort: Balanced

@thinkall Li Jiang (thinkall) 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.

Whole-PR review at 3708aab7453614f3b6a35925f9d70d960e4b27f4: the stronger group-presence checks help, but two verified issues remain.

  • Group identity: np.asarray in flaml/automl/task/generic_task.py:265-268 turns distinct integer 1 and string "1" labels into the same string. Actual caller-supplied holdout metrics preserve those identities on main but receive only string labels on both this head and its predecessor. This is a remaining whole-PR regression, not a new production change in the latest test-only commit.
  • Assertion cardinality: the new CV helper accepts a repeated validation row because it counts sets. Appending an extra captured validation-group label also passes the current supplied-validation test, whereas the predecessor rejects it. Count the raw validation IDs and assert exact label-vector lengths.

pd.Index CV and range holdout still fail on current, predecessor and main; those are inherited array-like limitations, not newly introduced regressions. Targeted current suites passed 48 tests with 2 skips across the two native stacks. This does not establish full supported-version or optional-dependency coverage.

The Low skill verdict remains issues found. Evidence is retained locally only; no review outputs are pushed to this PR.

Posted by thinkall-agent-auto-reviewer

…ws and labels exactly

np.asarray turned a list holding the integer 1 and the string "1" into strings, so both labels reached the metric as "1". Labels that numpy would convert that way are kept as an object array. The CV partition test now counts the raw validation ids and the supplied-validation test checks the exact label-vector lengths.

Copilot AI 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.

🟡 Changes recommended

Mixed integer/string validation group labels can crash ranking evaluation because group_counts() sorts incomparable types, and the added classification test does not cover this path.

1 open issue

Review effort: Balanced

Comment thread flaml/automl/task/generic_task.py Outdated
Comment on lines +276 to +278
if arr.dtype.kind in "US" and any(not isinstance(g, str) for g in groups):
# numpy converted labels of different types (e.g. 1 and "1") to one string type: keep them as they are
arr = np.asarray(groups, dtype=object)

@thinkall Li Jiang (thinkall) 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.

Review of author head 8623543461c9449192fe763f78f28c4e948e4cac.

The validation-label fix and stronger fold/cardinality assertions are useful, but mixed training group labels still do not work.

With eight distinct groups [0, 1, 2, 3, "0", "1", "2", "3"] repeated 25 times, real RF AutoML fits with split_type="group", max_iter=2 and either holdout or two-fold CV now raise TypeError: '<' not supported between instances of 'str' and 'int'. The new GenericTask._group_labels_as_array preserves the identities as an object array, but the splitter then sorts the heterogeneous raw values. Homogeneous string controls train successfully on both native stacks. The new mixed-type regression only mixes groups_val, not training groups.

Please use stable split-only codes while preserving the original labels for metrics, and cover mixed training labels in both holdout and CV. The predecessor ran but coalesced the identities; main rejects these list fixtures differently, so this is not a claim that main previously supported them correctly.

The focused current suite passed 52 cases with two deliberate splitter skips; the new selected predecessor controls fail on both stacks. Unrelated optional/OpenML integration diagnostics are retained separately and are not attributed to this change.

Current selected-scope independent coverage: 6/6; whole-PR scope. No contributor source or tests were edited; review evidence is retained locally and is not pushed to this PR.

Posted by thinkall-agent-auto-reviewer

Copilot AI 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.

🟡 Changes recommended

Unconditional use of np.unique on pandas-on-Spark group labels breaks Spark group cross-validation before the Spark-specific splitter is reached.

4 open issues

Review effort: Balanced

assert len(state.groups_all) == y_train_all_size, "the length of groups must match the number of examples"
assert (
len_labels(state.groups_all) >= n_splits
len_labels(group_split_codes(state.groups_all)) >= n_splits
Li Jiang (thinkall) and others added 2 commits December 3, 2026 02:37
…lit_codes

np.unique cannot iterate a pandas-on-Spark Series, so group cross-validation failed in prepare_data before reaching the Spark-aware len_labels. Return such labels unchanged.
… or coding groups

group_counts and group_split_codes passed a list straight to np.unique, which coerces [0, 0, "0"] to strings, and NaN in float labels was counted as a group. Convert lists to an object array and check for missing labels first.

Copilot AI 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.

🔵 Needs a closer look

Mixed numeric list/tuple group labels can lose precision during float64 conversion, causing distinct groups to merge in splitting and ranking query counts to be silently combined. Separately, Spark group CV fails during preparation when groups is a pandas-on-Spark Series because np.unique attempts unsupported iteration before reaching the Spark-aware path.

4 open issues

Review effort: Balanced

Lists, tuples, arrays and Series of group labels go through _group_label_array: object dtype for lists (no float64 merge of 2**53 and 2**53 + 1) and a ValueError for missing labels, instead of an error inside the metric that is reported as an infinite loss.
@sohailshk

Copy link
Copy Markdown
Author
  • Fixed our Spark CI failure: np.unique was being called on a pandas-on-Spark Series. Spark labels now skip that path.
  • group_counts([0,0,"0","0","0"]) previously returned [5]; it now correctly returns [2,3].
  • NaN labels are rejected.
  • [2**53, 2**53+1, 0.5, 7] no longer merges distinct labels.
  • Validation now happens once in prepare_data.
  • NaN in groups_val previously resulted in best_loss=inf; it now raises a clear error.
  • Added 4 tests, all red before and green after.
  • PySpark itself was not run locally.

Copilot AI 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.

@thinkall Li Jiang (thinkall) 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.

Complete current foreign group-label feature, reviewed at 9607fc90ac13b8865788c7d0e89315d5f01340c7 against frozen baseline cc32fc3274aa6621614d4971ad74967181d4d564.

The list/tuple/non-default-index Series cases and the new exact-label/missing-value cases pass on both pinned stacks (76 passes, two documented holdout/splitter skips).

I independently checked the other reported container/shape concerns against the predecessor and main: pd.Index CV, composite tuple keys and partial-order frozenset labels already fail there. These are retained as pre-existing or internal-helper hardening notes, not new public-pipeline regressions or requests to broaden this patch. The standalone group_split_codes raw-list path can still lose large-integer precision, while the supported AutoML.fit path normalizes first and passes the new four-group CV regression. Default float/Decimal ordering and ragged object-tuple error subclaims were not reproduced.

Independent selected-scope coverage: 5/6; original findings, priorities and failed attempts remain recorded. This is not a clean whole-PR approval.

At 2026-12-03T06:14:24.077602+00:00, checks=SUCCESS; actual current-head workflows: docs=completed/success; Code formatting=completed/success; Build=completed/success. Workflow authorization is not CI success. Main advanced during frozen review; that later integration is not reviewed or treated as approval clearance. No contributor source was changed and no review outputs were pushed here.

Posted by thinkall-agent-auto-reviewer

Copilot AI 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.

Copilot AI 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.

@thinkall Li Jiang (thinkall) 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.

Base integration inspected at 7632c888832dca17638d67528b60d4217eeb4f68. The branch update is an exact merge with current main, with no new edits to the existing feature. Only the imported foreign SVC cloning and forest preprocessing changes were selected; the separate own-authored release docs/version changes are excluded. The selected integration tests pass14cases on each pinned stack (28total).

Independent automated review remains blocked by the earlier review execution safety limit. No new reviewer or standalone artifact writer was dispatched for this PR. Native checks and merge/projection proofs are not whole-PR code-review signoff, and a base merge does not reset any missing-review or safety bound. Existing feature findings and incomplete whole-PR coverage remain held; current-head CI and peer/thread gates are separate requirements. This is a formal status COMMENT, not approval. No review outputs were pushed here.

Posted by thinkall-agent-auto-reviewer

Copilot AI 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.

🟡 Changes recommended

The helper runs a full np.unique sort on ordinary numeric and string label arrays even though it returns them unchanged. Because evaluate_model_CV calls it for every evaluated configuration, existing group-CV workloads now repeatedly sort the entire label array just to check sortability.

5 open issues

Review effort: Balanced

Comment thread flaml/automl/data.py
Comment on lines +795 to +797
labels = _group_label_array(groups)
try:
np.unique(labels)

@thinkall Li Jiang (thinkall) 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.

Base integration inspected at 818b96a090673a2a8a430d329effada9e66d277b. The branch update is an exact merge with current main, with no new edits to the existing feature. Only the imported foreign FLOW2 categorical-choice correction was selected; the separate own-authored CD/workflow and package-metadata changes are excluded. The selected integration tests pass14cases on each pinned stack (28total).

Independent automated review remains blocked by the earlier review execution safety limit. No new reviewer or standalone artifact writer was dispatched for this PR. Native checks and merge/projection proofs are not whole-PR code-review signoff, and a base merge does not reset any missing-review or safety bound. Existing feature findings and incomplete whole-PR coverage remain held; current-head CI and peer/thread gates are separate requirements. This is a formal status COMMENT, not approval. No review outputs were pushed here.

Posted by thinkall-agent-auto-reviewer

This branch has not been deployed

No deployments
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.

3 participants