Repository navigation
Conversation
|
As another example of problems identified by this testing mechanism: scikit-learn/sklearn/model_selection/_search.py Line 1091 in ffc6cdc self, via the context callbacks?).
I need to understand the code significantly better to have a sense of what's going on or how to fix it (naive |
|
Thank you for the PR, @itamarst, and for helping improve scikit-learn.
Could you please open an issue first? That would be a better place to explain the proposal and discuss the overall scope with the maintainers before continuing further with the implementation. If possible, including a minimal reproducible example demonstrating the thread-safety issue(s) this proposal aims to address would also be very helpful. |
|
Figuring out ways to convince ourselves and our users that you can safely use scikit-learn with free threading is important (and hard work!). My immediate thoughts (besides excitement that someone is excited to tackle this):
|
|
Thanks for working on this @itamarst !
recently I noticed that the free-threading CI job frequently fails. I've fixed a few tests but it seems there are more. I think a good first step would be to make sure the test suite itself is thread safe.
Well it's not that simple. These are public methods (https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.BallTree.html#sklearn.neighbors.BallTree.get_tree_stats). Removing them would need to go through a deprecation cycle. There was an earlier attempt (#19884) that didn't go through (it was also related with possible performance issues with these fields).
I believe this is expected. The estimator holds a attribute that has a tree structure, which grows during fit. different threads modify the tree but involve different nodes. It would be interesting to check that all operations there are thread safe in free-threading python. |
|
Thanks, @itamarst. That's an interesting way to detect this class of problems but as @jeremiedbb said above it can be subject to false positives: harmless (non-conflicting) mutations of the input arguments that are used as temporary datastructures by the parallel function. That being said, maybe the mutation of input arguments of a parallel function is a bad code pattern, and we should refactor our code to avoid them to make it easier to maintain this code in the future. But we need a clearer understanding the various tradeoffs that would entail in terms of code complexity and computational overhead. I ran the tests suite with the new pytest flag introduced in this branch and I confirm there are hundreds of tests failures but I suspect many are duplicates of the same candidate bug. I asked an agent to post process it to deduplicate root causes: Test reportPytest output post-processing script#!/usr/bin/env python3
"""Deduplicate pytest hash-mismatch AssertionError failures.
This script parses a pytest text log, finds failure blocks containing:
"AssertionError: Hash for object of type ... has changed",
then deduplicates by (scikit-learn call line, full exception message).
It writes a Markdown report grouped by full exception message.
"""
from __future__ import annotations
import argparse
import re
from collections import defaultdict
from pathlib import Path
ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
FAILURE_HEADER_RE = re.compile(r"^_{3,} .* _{3,}$")
TEST_HEADER_EXTRACT_RE = re.compile(r"^_{3,}\s*(.*?)\s*_{3,}$")
FILE_LOCATION_RE = re.compile(r"^[A-Za-z0-9_./-]+\.py:\d+:")
FILE_LOCATION_EXTRACT_RE = re.compile(r"^(?P<path>[A-Za-z0-9_./-]+\.py):(?P<line>\d+):")
HASH_MISMATCH_TOKEN = "AssertionError: Hash for object of type"
def read_clean_lines(path: Path) -> list[str]:
text = path.read_text(encoding="utf-8", errors="replace")
return [ANSI_ESCAPE_RE.sub("", ln.rstrip("\n")) for ln in text.splitlines()]
def split_failure_blocks(lines: list[str]) -> list[list[str]]:
blocks: list[list[str]] = []
i = 0
n = len(lines)
while i < n:
if FAILURE_HEADER_RE.match(lines[i]):
start = i
i += 1
while i < n and not FAILURE_HEADER_RE.match(lines[i]):
if lines[i].startswith("=") and "short test summary info" in lines[i].lower():
break
i += 1
blocks.append(lines[start:i])
else:
i += 1
return blocks
def extract_call_site(block: list[str]) -> tuple[str, str | None, int | None]:
"""Return (source_line, file_path, file_line) for the extracted call site."""
first_file_idx = None
for idx, ln in enumerate(block):
if FILE_LOCATION_RE.match(ln):
first_file_idx = idx
break
search_region = block[:first_file_idx] if first_file_idx is not None else block
call_idx = None
call = None
for idx, ln in enumerate(search_region):
if ln.startswith("> "):
candidate = ln[2:].strip()
if not candidate.startswith("raise AssertionError"):
call = candidate
call_idx = idx
break
if call is None:
for idx, ln in enumerate(block):
if ln.startswith("> "):
candidate = ln[2:].strip()
if not candidate.startswith("raise AssertionError"):
call = candidate
call_idx = idx
break
if call is None or call_idx is None:
return "", None, None
# Find the closest file location line after the call site line.
for ln in block[call_idx + 1 :]:
match = FILE_LOCATION_EXTRACT_RE.match(ln)
if match is not None:
return call, match.group("path"), int(match.group("line"))
# Fallback to first file location in block if no forward match exists.
for ln in block:
match = FILE_LOCATION_EXTRACT_RE.match(ln)
if match is not None:
return call, match.group("path"), int(match.group("line"))
return call, None, None
def parse_hash_mismatch_records(lines: list[str]) -> list[tuple[str, str, str | None, int | None, str]]:
records: list[tuple[str, str, str | None, int | None, str]] = []
for block in split_failure_blocks(lines):
header = block[0]
test_name_match = TEST_HEADER_EXTRACT_RE.match(header)
test_name = test_name_match.group(1) if test_name_match else header
message = None
for ln in block:
pos = ln.find(HASH_MISMATCH_TOKEN)
if pos >= 0:
message = ln[pos:]
break
if message is None:
continue
call_line, file_path, file_line = extract_call_site(block)
if not call_line:
continue
records.append((test_name, call_line, file_path, file_line, message))
return records
def render_markdown(
records: list[tuple[str, str, str | None, int | None, str]], source_log: Path
) -> str:
pair_counts: dict[tuple[str, str | None, int | None, str], int] = defaultdict(int)
for _test_name, call, file_path, file_line, msg in records:
pair_counts[(call, file_path, file_line, msg)] += 1
grouped: dict[str, list[tuple[str, str | None, int | None, int]]] = defaultdict(list)
for (call, file_path, file_line, msg), count in sorted(
pair_counts.items(), key=lambda item: (item[0][3], item[0][0], item[0][1] or "", item[0][2] or 0)
):
grouped[msg].append((call, file_path, file_line, count))
lines: list[str] = []
lines.append("# Deduplicated Hash-Mismatch AssertionError Report")
lines.append("")
lines.append(f"Source log: `{source_log.name}`")
lines.append("")
lines.append("## Summary")
lines.append("")
lines.append(f"- Total hash-mismatch failure blocks: {len(records)}")
lines.append(f"- Unique call-site + message pairs: {len(pair_counts)}")
lines.append(f"- Unique full exception messages: {len(grouped)}")
lines.append("")
lines.append("## Deduplicated Failures")
lines.append("")
for idx, message in enumerate(sorted(grouped.keys()), 1):
lines.append(f"### {idx}. Exception Message")
lines.append("")
lines.append(f"`{message}`")
lines.append("")
lines.append("Calls:")
lines.append("")
for call, file_path, file_line, count in sorted(
grouped[message], key=lambda it: (it[0], it[1] or "", it[2] or 0)
):
if file_path is not None and file_line is not None:
lines.append(
f"- [{count}x] Location: `{file_path}:{file_line}` | Source: `{call}`"
)
else:
lines.append(f"- [{count}x] Location: `unknown` | Source: `{call}`")
lines.append("")
return "\n".join(lines).rstrip() + "\n"
def main() -> None:
parser = argparse.ArgumentParser(
description=(
"Parse pytest.log and write a Markdown report of unique scikit-learn calls "
"that trigger hash-mismatch AssertionError failures."
)
)
parser.add_argument(
"--log",
type=Path,
default=Path("pytest.log"),
help="Path to pytest log file (default: pytest.log)",
)
parser.add_argument(
"--output",
type=Path,
default=Path("pytest_hash_mismatch_report.md"),
help="Output Markdown report path (default: pytest_hash_mismatch_report.md)",
)
args = parser.parse_args()
if not args.log.exists():
raise SystemExit(f"Log file not found: {args.log}")
clean_lines = read_clean_lines(args.log)
records = parse_hash_mismatch_records(clean_lines)
report = render_markdown(records, args.log)
args.output.write_text(report, encoding="utf-8")
print(f"Wrote {args.output} with {len(records)} matching failure blocks.")
if __name__ == "__main__":
main()There are also many I think that many of the problems in the report above still stem from the same root cause though. |
|
@ogrisel I have updated the prototype with some examples of annotating both inputs and classes for known thread safety (or bugginess). The annotations allow for quickly getting everything green in CI and then going item by item later to fix bugginess or document thread-safety if it's not immediately obvious how it's implemented. |
|
Thanks, I will try to find the time to review this today or early next week. |
|
To take this from sketch to something potentially mergeable, I would want to do the following at minimum:
|
|
As I'm starting to create PRs that turn on free-threading, testing for correctness is increasingly important. In order to make it easier to get this merged, I will likely refactor it to initially be a manual testing option one has to implement for specific classes, which means less noise and the ability to make its usage incremental. And then I can use it in PRs like #34659. |
|
#32753 is an example of limits of this approach, since |
Background
I am working for Quansight on a contract to improve free-threading/threading support in Scikit-Learn.
To ensure thread-safety, it's useful to have test infrastructure that will provide:
A good starting point here is focusing on operations that are already parallel, where users might reasonably expect to be able to turn threading on as a
joblibbackend and have it Just Work. These operations also work in a very particular way: create some tasks, run them in a worker pool, get back the results of the tasks.What can go wrong in this particular idiom? Switching from a process pool to a thread pool introduces thread-safety issues with the inputs to a
Parallel()operation: whereas mutating in a process is fine, mutating in a thread can affect other threads, or future interactions with the object in the main thread.This suggests a starting point for a invariant to be using in testing: the inputs to a
Parallel()operation that can correctly run with both process and thread pools should not change when the function is run.What this PR does
When
pytestis run with a new--thread-safety-testingflag:Parallel()switches to running using a thread pool.This testing mechanism causes many tests to fail, suggesting objects are being mutated in the thread pool. At least in some cases this would suggest data races.
To demonstrate one of the (potential) problems it identifies, I fixed a real problem it identified: in
BinaryTree/KDTree, certain C-level attributes were being modified in a non-thread-safe way. In normal Python with a GIL this was maybe safe, depending where the GIL was released. In free-threaded code this is definitely not safe.In practice these attributes weren't actually used by sklearn, so this wouldn't have impacted users, and removing them altogether seemed the easiest way to solve the problem.
In the short term I will keep going through the identified problems to see if there are any that impact real-world usage. But even if most of the currently found issues are minor, the real value will be having this run in CI in the future, because it will catch many thread-safety regressions before they get merged, as thread pools become more common.
Next steps
I am opening this PR as a draft for discussion purposes. If this approach is acceptable, future steps (in this PR, or more likely spread across multiple PRs) would likely include:
_parallel_testing.py.Reference Issues/PRs
None for now.
AI usage disclosure
I did not use "AI" assistance.
Any other comments?