Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

Test accuracy_conformance fix (#31725)

Mingyu Kim5e3914a1d0cf
diff --git a/tests/llm/accuracy_conformance.py b/tests/llm/accuracy_conformance.py
index f5ac3405006..141bccaeecb 100644
--- a/tests/llm/accuracy_conformance.py
+++ b/tests/llm/accuracy_conformance.py
@@ -18,40 +18,40 @@ logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Test Configuration Catalog
-TEST_CATALOG = {
- "TinyLlama/TinyLlama-1.1B-Chat-v1.0": {
+def add_test_case(catalog, model, gpu_int8_ref, gpu_int4_ref, cpu_int8_ref, cpu_int4_ref, threshold = 0.03):
+ catalog[model] = {
"GPU": {
- "INT8": {"reference": 0.98, "threshold": 0.03},
- "INT4": {"reference": 0.71, "threshold": 0.03},
+ "INT8": {"reference": gpu_int8_ref, "threshold": threshold},
+ "INT4": {"reference": gpu_int4_ref, "threshold": threshold},
},
"CPU": {
- "INT8": {"reference": 0.94, "threshold": 0.03},
- "INT4": {"reference": 0.77, "threshold": 0.03},
+ "INT8": {"reference": cpu_int8_ref, "threshold": threshold},
+ "INT4": {"reference": cpu_int4_ref, "threshold": threshold},
},
- },
- "Qwen/Qwen2-0.5B-Instruct": {
- "GPU": {
- "INT8": {"reference": 0.86, "threshold": 0.03},
- "INT4": {"reference": 0.74, "threshold": 0.03},
- },
- "CPU": {
- "INT8": {"reference": 0.82, "threshold": 0.03},
- "INT4": {"reference": 0.68, "threshold": 0.03},
- },
- },
-}
+ }
+
+TEST_CATALOG = {}
+NOTEST=0.0
+# NAME, GPU_i8, GPU_i4, CPU_i8, CPU_i4
+add_test_case(TEST_CATALOG, "TinyLlama/TinyLlama-1.1B-Chat-v1.0", NOTEST, NOTEST, 0.94, 0.77)
+add_test_case(TEST_CATALOG, "Qwen/Qwen2-0.5B-Instruct", NOTEST, NOTEST, 0.82, 0.68)
# Extract configuration from catalog
MODEL_IDS = list(TEST_CATALOG.keys())
-DEVICES = list(set(device for model_config in TEST_CATALOG.values()
+DOWNLOADED_MODELS = set()
+DEVICES = list(set(device for model_config in TEST_CATALOG.values()
for device in model_config.keys()))
-NUMBER_OF_SAMPLES = 15
METRIC_OF_INTEREST = "similarity"
PREC_INT8 = "INT8"
PREC_INT4 = "INT4"
-GPU_SUFFIX = 0 # Suffix to append to device name (e.g., '.1' for GPU.1). To be replaced by option
-DO_NOT_CLEANUP = False
+# Get configuration from environment variables (set by pytest options)
+NUMBER_OF_SAMPLES = int(os.environ.get("PYTEST_SAMPLES", "15"))
+GPU_SUFFIX = int(os.environ.get("PYTEST_GPU_SUFFIX", "0"))
+CLEANUP_AFTER_TEST = os.environ.get("PYTEST_DO_NOT_CLEANUP", "false").lower() == "false"
+
+# Log current configuration
+logger.info(f"Configuration: SAMPLES={NUMBER_OF_SAMPLES}, GPU_SUFFIX={GPU_SUFFIX}, CLEANUP_AFTER_TEST={CLEANUP_AFTER_TEST}")
def get_reference(model_id, device, precision):
"""Get reference value from catalog"""
@@ -64,20 +64,18 @@ def get_threshold(model_id, device, precision):
def get_tmp_dir():
"""Get temporary directory based on cleanup preference"""
# Check environment variable set by pytest option
- do_not_cleanup = DO_NOT_CLEANUP
-
- if do_not_cleanup:
+ cleanup_after_test = CLEANUP_AFTER_TEST
+
+ if cleanup_after_test:
+ # Use temp directory when cleanup is enabled
+ tmp_dir = tempfile.mkdtemp(dir=os.getcwd())
+ else:
# Use fixed directory by default (could use tempfile.mkdtemp for true temporary)
tmp_dir = os.path.join(os.getcwd(), "test_models_cache")
os.makedirs(tmp_dir, exist_ok=True)
- else:
- # Use temp directory when cleanup is disabled
- tmp_dir = tempfile.mkdtemp(dir=os.getcwd())
logger.info(f"Using directory: {tmp_dir}")
return tmp_dir
-tmp_dir = get_tmp_dir()
-
def get_model_path(model_id, prec):
"""
Returns the path to the model based on its id and precision.
@@ -90,52 +88,82 @@ def get_gt_path(model_id, use_chat_template):
"""
return os.path.join(tmp_dir, f"{model_id.replace('/', '_')}_gt_{NUMBER_OF_SAMPLES}_{'chat_template' if use_chat_template else 'no-chat-template'}.json")
-def init_test_scope():
- test_scope = []
+def setup_model(model_id):
+ """
+ Download and prepare models (original, INT8, INT4) and ground truth data.
+ Only downloads if not already present.
+ """
+ if model_id in DOWNLOADED_MODELS:
+ logger.info(f"Model {model_id} already prepared, skipping setup")
+ return
- for model_id in MODEL_IDS:
- logger.info(f"Downloading and quantizing model: {model_id}")
- model = AutoModelForCausalLM.from_pretrained(model_id)
- tokenizer = AutoTokenizer.from_pretrained(model_id)
- model_path = get_model_path(model_id, "org")
+ logger.info(f"Setting up model: {model_id}")
+
+ # Download original model
+ model = AutoModelForCausalLM.from_pretrained(model_id)
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
+
+ # Save original model
+ model_path = get_model_path(model_id, "org")
+ if not os.path.exists(model_path):
+ logger.info(f"Saving original model: {model_path}")
model.save_pretrained(model_path)
tokenizer.save_pretrained(model_path)
- ov_tokenizer, ov_detokenizer = convert_tokenizer(tokenizer, with_detokenizer=True)
-
- int8_model_path = get_model_path(model_id, PREC_INT8)
- # If directory exists, do not quantize again. It is for local development purpose. CI should re-generate it everytime.
- if not os.path.exists(int8_model_path):
- logger.info(f'Saving int8 OpenVINO model: {int8_model_path}')
- ov_model = OVModelForCausalLM.from_pretrained(model_path, load_in_8bit=True)
- ov_model.save_pretrained(int8_model_path)
- tokenizer.save_pretrained(int8_model_path)
- del ov_model
- save_model(ov_tokenizer, os.path.join(int8_model_path, "openvino_tokenizer.xml"))
- save_model(ov_detokenizer, os.path.join(int8_model_path, "openvino_detokenizer.xml"))
- gc.collect()
-
- int4_model_path = get_model_path(model_id, PREC_INT4)
- if not os.path.exists(int4_model_path):
- logger.info(f'Quantizing model to INT4: {int4_model_path}')
- quantization_config = OVWeightQuantizationConfig(bits=4, ratio=0.8)
- quantized_model = OVModelForCausalLM.from_pretrained(
- model_path, quantization_config=quantization_config
- )
- quantized_model.save_pretrained(int4_model_path)
- tokenizer.save_pretrained(int4_model_path)
- del quantized_model
- save_model(ov_tokenizer, os.path.join(int4_model_path, "openvino_tokenizer.xml"))
- save_model(ov_detokenizer, os.path.join(int4_model_path, "openvino_detokenizer.xml"))
- gc.collect()
-
- set_seed(42)
- use_chat_template = False # (tokenizer is not None and tokenizer.chat_template is not None)
- gt_path = get_gt_path(model_id, use_chat_template)
- if not os.path.exists(gt_path):
- evaluator = wwb.Evaluator(base_model=model, tokenizer=tokenizer, num_samples=NUMBER_OF_SAMPLES, use_chat_template=use_chat_template)
- logger.info(f'{gt_path} does not exist, creating ground truth data...')
- evaluator.dump_gt(gt_path)
+ # Convert tokenizer for OpenVINO
+ ov_tokenizer, ov_detokenizer = convert_tokenizer(tokenizer, with_detokenizer=True)
+
+ # Prepare INT8 model
+ int8_model_path = get_model_path(model_id, PREC_INT8)
+ if not os.path.exists(int8_model_path):
+ logger.info(f'Creating INT8 OpenVINO model: {int8_model_path}')
+ ov_model = OVModelForCausalLM.from_pretrained(model_path, load_in_8bit=True)
+ ov_model.save_pretrained(int8_model_path)
+ tokenizer.save_pretrained(int8_model_path)
+ del ov_model
+ save_model(ov_tokenizer, os.path.join(int8_model_path, "openvino_tokenizer.xml"))
+ save_model(ov_detokenizer, os.path.join(int8_model_path, "openvino_detokenizer.xml"))
+ gc.collect()
+
+ # Prepare INT4 model
+ int4_model_path = get_model_path(model_id, PREC_INT4)
+ if not os.path.exists(int4_model_path):
+ logger.info(f'Creating INT4 OpenVINO model: {int4_model_path}')
+ quantization_config = OVWeightQuantizationConfig(bits=4, ratio=0.8)
+ quantized_model = OVModelForCausalLM.from_pretrained(model_path, quantization_config=quantization_config)
+ quantized_model.save_pretrained(int4_model_path)
+ tokenizer.save_pretrained(int4_model_path)
+ del quantized_model
+ save_model(ov_tokenizer, os.path.join(int4_model_path, "openvino_tokenizer.xml"))
+ save_model(ov_detokenizer, os.path.join(int4_model_path, "openvino_detokenizer.xml"))
+ gc.collect()
+
+ # Prepare ground truth data
+ set_seed(42)
+ use_chat_template = False # (tokenizer is not None and tokenizer.chat_template is not None)
+ gt_path = get_gt_path(model_id, use_chat_template)
+ if not os.path.exists(gt_path):
+ logger.info(f'Creating ground truth data: {gt_path}')
+ evaluator = wwb.Evaluator(
+ base_model=model,
+ tokenizer=tokenizer,
+ num_samples=NUMBER_OF_SAMPLES,
+ use_chat_template=use_chat_template
+ )
+ evaluator.dump_gt(gt_path)
+
+ # Mark model as downloaded
+ DOWNLOADED_MODELS.add(model_id)
+ logger.info(f"Model setup completed: {model_id}")
+
+def init_test_scope():
+ """
+ Initialize test scope with all model/device/precision combinations.
+ Model setup is handled separately by setup_model().
+ """
+ test_scope = []
+
+ for model_id in MODEL_IDS:
# Generate test cases for all device/precision combinations in catalog
for device in TEST_CATALOG[model_id].keys():
for precision in TEST_CATALOG[model_id][device].keys():
@@ -143,17 +171,22 @@ def init_test_scope():
return test_scope
-
def teardown_module():
"""Clean up temporary directory based on cleanup option"""
- do_not_cleanup = DO_NOT_CLEANUP # to be replaced by pytest option
+ cleanup_after_test = CLEANUP_AFTER_TEST
- if do_not_cleanup:
- logger.info(f"Cleanup disabled - preserving directory: {tmp_dir}")
- else:
+ if cleanup_after_test:
logger.info(f"Deleting temporary directory: {tmp_dir}")
- shutil.rmtree(tmp_dir)
+ if os.path.exists(tmp_dir):
+ # removing directory may fail because of mmap of the model
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+ logger.info(f"Deleted(may have failed): {tmp_dir}")
+ else:
+ logger.info(f"Directory already removed: {tmp_dir}")
+ else:
+ logger.info(f"Cleanup disabled - preserving directory: {tmp_dir}")
+tmp_dir = get_tmp_dir()
test_scope = init_test_scope()
@@ -162,6 +195,17 @@ test_scope = init_test_scope()
test_scope,
)
def test_accuracy_conformance(model_id, precision, device):
+ # Get expected values from catalog (use original device for lookup)
+ expected_reference = get_reference(model_id, device, precision)
+ if expected_reference == NOTEST:
+ pytest.xfail(f'Test is skipped for {model_id}, {precision}, {device}. Ticket 172236')
+ return
+
+ # Ensure model is set up
+ if model_id not in DOWNLOADED_MODELS:
+ logger.info(f"Model {model_id} not found in downloaded models, setting up now...")
+ setup_model(model_id)
+
# os.environ["OV_GPU_DYNAMIC_QUANTIZATION_THRESHOLD"] = "1"
task = 'text'
@@ -176,9 +220,9 @@ def test_accuracy_conformance(model_id, precision, device):
tokenizer = AutoTokenizer.from_pretrained(model_path)
- use_chat_template = False #(tokenizer is not None and tokenizer.chat_template is not None)
- gt_data = get_gt_path(model_id, use_chat_template)
+ use_chat_template = False # (tokenizer is not None and tokenizer.chat_template is not None)
+ gt_data = get_gt_path(model_id, use_chat_template)
evaluator = wwb.Evaluator(
base_model=None,
gt_data=gt_data,
@@ -194,8 +238,6 @@ def test_accuracy_conformance(model_id, precision, device):
metric = all_metrics[METRIC_OF_INTEREST].values[0]
evaluator.dump_predictions(os.path.join(tmp_dir, f"{get_model_path(model_id, precision)}_{actual_device}_target.csv"))
- # Get expected values from catalog (use original device for lookup)
- expected_reference = get_reference(model_id, device, precision)
threshold = get_threshold(model_id, device, precision)
abs_metric_diff = abs(expected_reference - metric)
diff --git a/tests/llm/conftest.py b/tests/llm/conftest.py
new file mode 100644
index 00000000000..ba50d7037f7
--- /dev/null
+++ b/tests/llm/conftest.py
@@ -0,0 +1,19 @@
+import os
+
+def pytest_addoption(parser):
+ parser.addoption("--do_not_cleanup", action="store_true", default=False, help="Do not cleanup temporary files after test completion")
+ parser.addoption("--gpu_suffix", action="store", default="0", help="Suffix to append to GPU device name (e.g., '1' for GPU.1)")
+ parser.addoption("--samples", action="store", default=15, type=int, help="Number of samples for evaluation")
+
+def pytest_configure(config):
+ """Set environment variables based on pytest options"""
+ # Set cleanup option
+ if config.getoption("--do_not_cleanup"):
+ os.environ["PYTEST_DO_NOT_CLEANUP"] = "true"
+ else:
+ os.environ["PYTEST_DO_NOT_CLEANUP"] = "false"
+
+ # Set other options
+ os.environ["PYTEST_GPU_SUFFIX"] = str(config.getoption("--gpu_suffix"))
+ os.environ["PYTEST_SAMPLES"] = str(config.getoption("--samples"))
+