mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-10-31 07:43:00 +08:00
### What does this PR do? - Add secure checkpoint loading support using `torch.serialization.add_safe_globals([cls])`. This also removes 1 existing pickle usage. - Remove hard-coded `trust_remote_code=True` - Replaces https://github.com/NVIDIA/Model-Optimizer/pull/1056 by @RinZ27 ### Testing <!-- Mention how have you tested your change if applicable. --> CICD tests ran ### Before your PR is "*Ready for review*" Make sure you read and follow [Contributor guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md) and your commits are signed (`git commit -s -S`). Make sure you read and follow the [Security Best Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors) (e.g. avoiding hardcoded `trust_remote_code=True`, `torch.load(..., weights_only=False)`, `pickle`, etc.). - Is this change backward compatible?: ✅ <!--- If ❌, explain why. --> - If you copied code from any other sources or added a new PIP dependency, did you follow guidance in `CONTRIBUTING.md`: ✅ <!--- Mandatory --> - Did you write any new necessary tests?: ✅ <!--- Mandatory for new features or examples. --> - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ✅ <!--- Only for new features, API changes, critical bug fixes or backward incompatible changes. --> ### Additional Information NVBug: 5999336 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added safe checkpoint save/load helpers and a --trust_remote_code CLI flag in examples to control remote-code loading. * **Bug Fixes** * Checkpoint loading now defaults to safer, weights-only semantics to reduce arbitrary-code exposure. * **Documentation** * CHANGELOG updated with security guidance and opt-in procedure for unsafe checkpoint loading. * **Tests** * New unit tests validating the safe-load behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: RinZ27 <222222878+RinZ27@users.noreply.github.com> Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com> Co-authored-by: RinZ27 <222222878+RinZ27@users.noreply.github.com>
109 lines
4.0 KiB
Python
109 lines
4.0 KiB
Python
# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
# SPDX-License-Identifier: Apache-2.0
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
import argparse
|
|
|
|
from accelerate import Accelerator
|
|
from datasets import load_dataset
|
|
from tqdm import tqdm
|
|
from transformers import AutoTokenizer
|
|
|
|
import modelopt.torch.opt as mto
|
|
from modelopt.torch.speculative.plugins.transformers import HFARValidation
|
|
from modelopt.torch.speculative.utils import load_vlm_or_llm
|
|
|
|
mto.enable_huggingface_checkpointing()
|
|
|
|
|
|
def validate_ar(model, tokenizer, ds, steps=3, osl=20, num_samples=80, device=None):
|
|
validator = HFARValidation(model, tokenizer)
|
|
num_samples = min(num_samples, len(ds))
|
|
ars = []
|
|
for i in tqdm(range(num_samples), desc="Validating AR"):
|
|
prompt = ds[i]["prompt"][0]
|
|
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
|
|
# Apply chat template to the prompt, continuing with assistant response
|
|
if hasattr(tokenizer, "apply_chat_template"):
|
|
chat_messages = [
|
|
{"role": "user", "content": prompt},
|
|
]
|
|
prompt = tokenizer.apply_chat_template(
|
|
chat_messages, tokenize=False, add_generation_prompt=True
|
|
)
|
|
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
|
|
if device:
|
|
input_ids = input_ids.to(device)
|
|
|
|
# validate AR
|
|
_, ar = validator.validate(osl, input_ids=input_ids, steps=steps)
|
|
ars.append(ar)
|
|
return ars
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--model_path", type=str, required=True, help="Path to model directory")
|
|
parser.add_argument("--trust_remote_code", action="store_true", help="Trust remote code")
|
|
parser.add_argument("--steps", type=int, default=3, help="Steps for AR validation")
|
|
parser.add_argument(
|
|
"--osl", type=int, default=32, help="Output sequence length for AR validation"
|
|
)
|
|
parser.add_argument(
|
|
"--num_samples", type=int, default=80, help="Number of MT-Bench samples to use"
|
|
)
|
|
parser.add_argument(
|
|
"--ar_lower_bound",
|
|
type=float,
|
|
default=None,
|
|
help="AR lower bound for validation. If provided, will throw error if AR is below threshold.",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
accelerator = Accelerator()
|
|
# Load model and tokenizer
|
|
model = load_vlm_or_llm(
|
|
args.model_path, device_map="auto", trust_remote_code=args.trust_remote_code
|
|
)
|
|
tokenizer = AutoTokenizer.from_pretrained(
|
|
args.model_path, trust_remote_code=args.trust_remote_code
|
|
)
|
|
model.eval()
|
|
model = accelerator.prepare(model)
|
|
|
|
# Load MT-Bench prompts from HuggingFace
|
|
ds = load_dataset("HuggingFaceH4/mt_bench_prompts")["train"]
|
|
ars = validate_ar(
|
|
model, tokenizer, ds, args.steps, args.osl, args.num_samples, accelerator.device
|
|
)
|
|
# Optionally, throw error if AR is below lower bound
|
|
if args.ar_lower_bound:
|
|
mean_ar = sum(ars) / len(ars)
|
|
if mean_ar < args.ar_lower_bound:
|
|
raise ValueError(
|
|
f"AR is below lower bound {args.ar_lower_bound}. Mean AR: {mean_ar:.4f}"
|
|
)
|
|
# Print results
|
|
if ars and accelerator.is_main_process:
|
|
avg_ar = sum(ars) / len(ars)
|
|
print("\n==== AR Validation Results on MT-Bench ====")
|
|
print(f"Number of samples: {len(ars)}")
|
|
print(f"Output Sequence Length: {args.osl}")
|
|
print(f"Steps: {args.steps}")
|
|
print(f"Average AR: {avg_ar:.4f}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|