Skip to content

Commit 09f14b2

Browse files
Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
1 parent a5d845c commit 09f14b2

6 files changed

Lines changed: 28 additions & 11 deletions

File tree

examples/benchmarks/tensorrt_inference_performance.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,12 @@ def run_huggingface_benchmark(model_identifier, precision='fp16', batch_size=32,
9191
parser.add_argument('--iterations', type=int, default=2048)
9292
args = parser.parse_args()
9393

94+
if args.model_source == 'huggingface' and args.precision == 'int8':
95+
parser.error(
96+
'--precision int8 is not supported with --model_source huggingface '
97+
'(no calibration data / Q-DQ ONNX is generated). Use fp16 or fp32.'
98+
)
99+
94100
if args.model_source == 'huggingface':
95101
run_huggingface_benchmark(
96102
args.model_identifier, args.precision, args.batch_size, args.seq_length, args.iterations

superbench/benchmarks/micro_benchmarks/_export_torch_to_onnx.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818

1919
class torch2onnxExporter():
2020
"""PyTorch model to ONNX exporter."""
21-
2221
def __init__(self):
2322
"""Constructor."""
2423
from transformers import BertConfig, GPT2Config, LlamaConfig
@@ -360,7 +359,6 @@ def _build_vision_export_inputs(self, model, batch_size, model_dtype, device):
360359
dynamic_axes = {'pixel_values': {0: 'batch_size'}, 'output': {0: 'batch_size'}}
361360

362361
class VisionModelWrapper(torch.nn.Module):
363-
364362
def __init__(self, model):
365363
super().__init__()
366364
self.model = model
@@ -398,7 +396,6 @@ def _build_nlp_export_inputs(self, model, batch_size, seq_length, device):
398396
}
399397

400398
class NLPModelWrapper(torch.nn.Module):
401-
402399
def __init__(self, model):
403400
super().__init__()
404401
self.model = model

superbench/benchmarks/micro_benchmarks/huggingface_model_loader.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,6 @@ class HuggingFaceModelLoader:
8989
``False``; enabling this turns ``--model_identifier`` into an RCE
9090
sink, so it is opt-in only.
9191
"""
92-
9392
def __init__(
9493
self,
9594
cache_dir: Optional[str] = None,
@@ -154,6 +153,11 @@ def load_model(
154153
# Reject malformed / path-like identifiers before any network or disk activity.
155154
validate_model_identifier(model_identifier)
156155

156+
# Fall back to CPU on hosts without CUDA so default device='cuda' callers don't fail.
157+
if device == 'cuda' and not torch.cuda.is_available():
158+
logger.warning('CUDA not available; falling back to CPU.')
159+
device = 'cpu'
160+
157161
try:
158162
load_kwargs = self._build_load_kwargs(torch_dtype, revision, kwargs)
159163

@@ -211,10 +215,12 @@ def _build_load_kwargs(self, torch_dtype, revision, extra_kwargs):
211215

212216
def _try_load_tokenizer(self, model_identifier, load_kwargs):
213217
"""Attempt to load a tokenizer; return None if the model has no associated tokenizer."""
218+
# Tokenizers don't accept model-only kwargs like torch_dtype/device_map; strip before passing.
219+
tokenizer_kwargs = {k: v for k, v in load_kwargs.items() if k not in ('torch_dtype', 'device_map')}
214220
try:
215221
logger.info('Loading tokenizer...')
216222
return AutoTokenizer.from_pretrained(
217-
model_identifier, trust_remote_code=self.allow_remote_code, **load_kwargs
223+
model_identifier, trust_remote_code=self.allow_remote_code, **tokenizer_kwargs
218224
)
219225
except Exception as e:
220226
logger.warning(f'Could not load tokenizer: {e}. Continuing without tokenizer.')
@@ -373,7 +379,15 @@ def estimate_param_count_from_config(hf_config) -> Optional[int]:
373379

374380
# Embeddings: token + (optional) position
375381
max_pos = getattr(hf_config, 'max_position_embeddings', 0)
376-
has_pos_embed = getattr(hf_config, 'position_embedding_type', None) not in ('rotary', None)
382+
pos_embed_type = getattr(hf_config, 'position_embedding_type', None)
383+
# When position_embedding_type is missing/None, default to assuming learned
384+
# position embeddings exist (common for BERT-style configs that omit the field).
385+
# Only skip the term when the type is explicitly rotary, or the config clearly
386+
# indicates RoPE/rotary via rope_theta/rotary_pct/rotary_emb_base.
387+
uses_rotary = pos_embed_type == 'rotary' or any(
388+
getattr(hf_config, attr, None) is not None for attr in ('rope_theta', 'rotary_pct', 'rotary_emb_base')
389+
)
390+
has_pos_embed = not uses_rotary
377391
embed_params = vocab * hidden
378392
if has_pos_embed and max_pos > 0:
379393
embed_params += max_pos * hidden

superbench/benchmarks/micro_benchmarks/ort_inference_performance.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def add_parser_arguments(self):
145145
default=False,
146146
required=False,
147147
help='Allow HuggingFace to execute model-repo Python (trust_remote_code=True). '
148-
'SECURITY: enables RCE from --model_identifier. Pin --revision <sha> when used.',
148+
'SECURITY: enables RCE from --model_identifier; only enable for trusted model identifiers.',
149149
)
150150

151151
def _preprocess(self):

superbench/benchmarks/micro_benchmarks/tensorrt_inference_performance.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def add_parser_arguments(self):
104104
default=False,
105105
required=False,
106106
help='Allow HuggingFace to execute model-repo Python (trust_remote_code=True). '
107-
'SECURITY: enables RCE from --model_identifier. Pin --revision <sha> when used.',
107+
'SECURITY: enables RCE from --model_identifier; only enable for trusted model identifiers.',
108108
)
109109

110110
@staticmethod
@@ -238,9 +238,10 @@ def _preprocess_huggingface_models(self):
238238
hf_config = AutoConfig.from_pretrained(
239239
self._args.model_identifier, trust_remote_code=allow_remote_code, **load_kwargs
240240
)
241-
precision_str = self._args.precision # already a string: 'fp16', 'fp32', 'int8'
241+
# ONNX export is always done in float32 (see _build_trtexec_command_for_hf), so gate
242+
# the pre-download check on fp32 memory regardless of the requested runtime precision.
242243
fits, _, _, _ = HuggingFaceModelLoader.check_memory_fits(
243-
self._args.model_identifier, hf_config, precision_str, mode='inference', token=hf_token
244+
self._args.model_identifier, hf_config, 'fp32', mode='inference', token=hf_token
244245
)
245246
if not fits:
246247
self._result.set_return_code(ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE)

tests/benchmarks/micro_benchmarks/test_huggingface_e2e.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
)
2929
class TestHuggingFaceE2E:
3030
"""End-to-end tests for HuggingFace model loading."""
31-
3231
@pytest.fixture
3332
def loader(self, tmp_path):
3433
"""Create a loader instance with an isolated per-test cache dir."""

0 commit comments

Comments
 (0)