perf: optimize license detection - #98
Open
saquibsaifee wants to merge 1 commit into
Open
Conversation
Contributor
Author
|
For reviewer reference, here is the script to measure the performance improvement locally: Measured Execution: Original Time: 0.82s import time
import logging
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError, EntryNotFoundError
import warnings
warnings.filterwarnings('ignore')
logging.getLogger("huggingface_hub").setLevel(logging.ERROR)
LICENSE_MAPPING = {
"apache license version 2.0": "Apache-2.0",
"mit license": "MIT",
"bsd 3-clause": "BSD-3-Clause"
}
def original_detect_license_from_file(model_id: str):
license_filenames = ["LICENSE", "LICENSE.txt", "LICENSE.md", "LICENSE.rst", "COPYING"]
for filename in license_filenames:
try:
file_path = hf_hub_download(repo_id=model_id, filename=filename)
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
snippet = f.read(4096).lower()
for header, spdx_id in LICENSE_MAPPING.items():
if header in snippet:
return spdx_id
return "UNKNOWN"
except (RepositoryNotFoundError, EntryNotFoundError):
continue
except Exception as e:
continue
return None
def optimized_detect_license_from_file(model_id: str):
license_filenames = ["LICENSE", "LICENSE.txt", "LICENSE.md", "LICENSE.rst", "COPYING"]
api = HfApi()
try:
repo_info = api.model_info(repo_id=model_id, files_metadata=False)
repo_filenames = {sibling.rfilename for sibling in repo_info.siblings}
except Exception:
return None
matching_files = [f for f in license_filenames if f in repo_filenames]
for matching_file in matching_files:
try:
file_path = hf_hub_download(repo_id=model_id, filename=matching_file)
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
snippet = f.read(4096).lower()
for header, spdx_id in LICENSE_MAPPING.items():
if header in snippet:
return spdx_id
return "UNKNOWN"
except Exception:
pass
return None
def run_benchmarks():
models = ["microsoft/phi-2", "google/gemma-7b", "mistralai/Mistral-7B-v0.1"]
print("Benchmarking Original...")
start = time.time()
for model in models:
original_detect_license_from_file(model)
orig_time = time.time() - start
print(f"Original Time: {orig_time:.2f}s")
print("\nBenchmarking Optimized...")
start = time.time()
for model in models:
optimized_detect_license_from_file(model)
opt_time = time.time() - start
print(f"Optimized Time: {opt_time:.2f}s")
if orig_time > 0:
print(f"\nImprovement: {((orig_time - opt_time) / orig_time) * 100:.2f}%")
if __name__ == "__main__":
run_benchmarks() |
Contributor
Author
|
@eaglei15 this PR is ready to be reviewed. |
Optimizes _detect_license_from_file by leveraging model_info to get the list of files in the repository. Instead of calling hf_hub_download in a blind loop for every possible license filename (triggering 404 network exceptions for misses), it now matches existing files locally and only downloads valid candidates. Safely traverses multiple license files if the first matching filename doesn't contain a valid SPDX header. Adds unit test coverage using unittest.mock. Removes benchmark_license.py script per PR review. Signed-off-by: saquibsaifee <saquibsaifee2@gmail.com>
saquibsaifee
force-pushed
the
perf/optimize-license-detection-11560173853639975489
branch
from
August 31, 2026 17:05
1341106 to
b3d2fc7
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
💡 What: The
_detect_license_from_filemethod has been optimized to query the Hugging Face hub for the model's file list usingmodel_info()before iterating over the potential license filenames. This ensures it only ever downloads matching files.🎯 Why: The previous implementation sequentially attempted to download every filename in
license_filenamesusinghf_hub_download, catching the 404 exception when the file wasn't found. For models missing standard licenses, this resulted in numerous wasted, latency-inducing network calls.📊 Measured Improvement:
I measured the performance improvement using a local Python script running over three different test models.
Original Time: 0.82s
Optimized Time: 0.28s
Improvement: 65.97% time reduction for sequential detections.