Skip to content

Commit c7d39f6

Browse files
committed
fix: use context managers for file I/O to prevent resource leaks
- 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>
1 parent 4e7b7a9 commit c7d39f6

3 files changed

Lines changed: 11 additions & 3 deletions

File tree

neural_compressor/evaluation/lm_eval/accuracy.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,8 @@ def cli_evaluate(args) -> None:
259259
eval_logger.info(f"Logging to Weights and Biases failed due to {e}")
260260

261261
if args.output_path:
262-
output_path_file.open("w", encoding="utf-8").write(dumped)
262+
with output_path_file.open("w", encoding="utf-8") as f:
263+
f.write(dumped)
263264

264265
if args.log_samples:
265266
for task_name, config in results["configs"].items():

neural_compressor/tensorflow/utils/utility.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,11 @@ def __exit__(self, type, value, traceback):
308308
os.close(self.orig_stream_dup)
309309
self.tmp_file.close()
310310

311+
def __del__(self):
312+
"""Ensure the file is closed if __exit__ was never called."""
313+
if hasattr(self, "tmp_file") and not self.tmp_file.closed:
314+
self.tmp_file.close()
315+
311316

312317
@singleton
313318
class TFSlimNetsFactory(object): # pragma: no cover

neural_compressor/torch/algorithms/layer_wise/utils.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,8 @@ def load_layer_wise_quantized_model(path): # pragma: no cover
129129
def load_tensor_from_shard(pretrained_model_name_or_path, tensor_name, prefix=None): # pragma: no cover
130130
"""Load tensor from shard."""
131131
path = _get_path(pretrained_model_name_or_path)
132-
idx_dict = json.load(open(os.path.join(path, "pytorch_model.bin.index.json"), "r"))["weight_map"]
132+
with open(os.path.join(path, "pytorch_model.bin.index.json"), "r") as f:
133+
idx_dict = json.load(f)["weight_map"]
133134
if tensor_name not in idx_dict.keys():
134135
if tensor_name.replace(f"{prefix}.", "") in idx_dict.keys():
135136
tensor_name = tensor_name.replace(f"{prefix}.", "")
@@ -176,7 +177,8 @@ def load_tensor_from_safetensors_shard(
176177
): # pragma: no cover
177178
"""Load tensor from shard."""
178179
path = _get_path(pretrained_model_name_or_path)
179-
idx_dict = json.load(open(os.path.join(path, "model.safetensors.index.json"), "r"))["weight_map"]
180+
with open(os.path.join(path, "model.safetensors.index.json"), "r") as f:
181+
idx_dict = json.load(f)["weight_map"]
180182
if tensor_name not in idx_dict.keys():
181183
if tensor_name.replace(f"{prefix}.", "") in idx_dict.keys():
182184
tensor_name = tensor_name.replace(f"{prefix}.", "")

0 commit comments

Comments
 (0)