Skip to content

fix: use context managers for file I/O to prevent resource leaks#2526

Open
lxcxjxhx wants to merge 2 commits into
intel:mainfrom
lxcxjxhx:fix/file-handle-resource-leaks
Open

fix: use context managers for file I/O to prevent resource leaks#2526
lxcxjxhx wants to merge 2 commits into
intel:mainfrom
lxcxjxhx:fix/file-handle-resource-leaks

Conversation

@lxcxjxhx

Copy link
Copy Markdown

Motivation

Several places in the codebase open files without using context managers (with statements), which can lead to resource leaks if exceptions occur or if the file handle is not explicitly closed. This is a common Python anti-pattern that can cause issues in long-running processes or when processing many files.

Changes

  • neural_compressor/torch/algorithms/layer_wise/utils.py: Replaced json.load(open(...)) with with open(...) as f: json.load(f) in load_tensor_from_shard and load_tensor_from_safetensors_shard to ensure file handles are properly closed after reading.

  • neural_compressor/tensorflow/utils/utility.py: Added __del__ method to CaptureOutputToFile class to ensure the temporary file is closed even when the object is not used as a context manager (i.e., __exit__ is never called).

  • neural_compressor/evaluation/lm_eval/accuracy.py: Replaced output_path_file.open("w", encoding="utf-8").write(dumped) with a with statement to ensure the output file is properly closed after writing.

Testing

These are defensive resource management improvements that do not change functional behavior. The existing test suite should continue to pass without modification.

- Replace json.load(open(...)) with context manager in layer_wise/utils.py
- Add __del__ method to CaptureOutputToFile to ensure file closure
- Use context manager for output_path_file.write() in accuracy.py

These changes ensure proper resource cleanup and prevent file handle leaks.

Signed-off-by: lxcxjxhx <lxcxjxhx@users.noreply.github.com>
@lxcxjxhx
lxcxjxhx force-pushed the fix/file-handle-resource-leaks branch from 3c674a3 to c7d39f6 Compare July 15, 2026 13:12
@lxcxjxhx

Copy link
Copy Markdown
Author

Hi @chensuyue @xin3he, could you please review this PR? The changes are defensive resource management improvements using context managers for file I/O.

I noticed the Model-Test-3x CI check is failing. This appears to be unrelated to the code changes (which only add context managers for file handling). Could you help investigate or re-run the CI if needed?

Thanks!

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.

2 participants