Skip to main content
Model scanning is part of HiddenLayer AI Supply Chain Security. A scan inspects model files for security risks, such as malicious code embedded in a serialized model, before you load or deploy them. The SDK uploads your model to HiddenLayer (or asks HiddenLayer to fetch it), waits for the scan to finish, and returns a scan report. Use model scanning when you:
  • Download a third-party model and want to check it before loading it.
  • Want to block risky models in a CI/CD pipeline.
  • Need a record of scan results for models stored in Hugging Face, AWS S3, or Azure Blob Storage.

Before you begin

  • Install the SDK and configure credentials. See Installation and Authentication and configuration.
  • Set HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET in your environment. Alternatively, set HIDDENLAYER_TOKEN to a bearer token. Every example on this page reads credentials from these variables. None of them hard-code secrets.
  • Your tenant must have AI Supply Chain Security enabled, and your client credential needs permission to use it.
The Python and TypeScript SDKs include helpers that download a model from Hugging Face, S3, or Azure Blob Storage before they scan it. Those helpers need storage packages that the SDK does not install. Install them only if you use the matching helper. The Java SDK has no download helpers: download the model with your cloud provider’s SDK and scan the downloaded file, or let HiddenLayer fetch it with the community scanner.

Understand the scan report

Every scan method returns a scan report, typed as ScanReportOfRecordV3:
  • Python: hiddenlayer.ScanReportOfRecordV3, a Pydantic model. Read fields as attributes, such as report.status. Don’t use hiddenlayer.ScanReport for type hints: since version 4 it is a different type.
  • TypeScript: HiddenLayerApi.ScanReportOfRecordV3, also exported as ScanReport. Fields keep the API’s names, such as report.summary.highest_severity.
  • Java: com.hiddenlayer.api.types.ScanReportOfRecordV3. Read fields with getters, such as report.getSummary().getHighestSeverity(). Optional fields return an Optional.
The fields you use most often are listed below by their API names: A file in an archive format also has one entry for each file inside it. For example, a PyTorch checkpoint such as pytorch_model.bin is a zip archive, so file_results lists pytorch_model.bin and entries such as pytorch_model.bin/archive/data.pkl. Each item in file_results[].detections includes severity (critical, high, medium, or low), category, description, rule_id, and mitre_atlas. It can also include evidence (for example, the function calls found in a pickle) and the mapping fields cve, cwe, cwe_href, and owasp. The API leaves a mapping field out when it doesn’t apply, so check that it is set before you read it. The risk, likelihood, and impact fields are optional too, and are usually absent.
The report also has top-level detection_count, file_count, files_with_detections_count, severity, and detection_categories fields. These are deprecated. Read the same values from summary instead, and use summary.highest_severity rather than summary.severity. Some older examples, including examples/demo.py in the Python SDK repository, still read the deprecated fields.
A scan that fails is returned, not raised as an exception. Always check the report’s status before you trust the summary. A failed scan may have zero detections only because the scan did not complete.

Choose a scan method

The Python and TypeScript scanners are client.model_scanner and client.modelScanner. In Java they are client.modelScanner() and client.communityScanner(). Every scan method waits until the scan finishes unless you turn that off: wait_for_results=False in Python, waitForResults: false in TypeScript, or .waitForResults(false) on the Java options builder. See Start a scan without waiting.

Scan a local file

Use the file scan to scan one model file, such as a .pkl, .pt, .h5, or .safetensors file. The SDK uploads the file in parts, tells HiddenLayer the upload is complete, and then polls until the scan finishes. The following program scans a file, prints the results, and exits with a non-zero code if the scan fails, a file can’t be scanned, or the scan finds a critical or high detection. You can run it as a CI gate: most CI systems fail the job when a step exits with a non-zero code. The SDK waits for the scan with no time limit, so set a timeout on the CI job, or use the polling loop in Wait with a time limit.
Expected result: the program prints the scan ID, status, highest threat level, and detection count. For each file it prints any detections. For a model with no detections, the status is done, the highest threat level is typically none, and the program exits with code 0. The model name and model version identify the model in the HiddenLayer Console. The version defaults to "1".

Scan a folder

Use the folder scan when a model consists of several files, such as a weights file plus configuration and tokenizer files. The SDK walks the folder recursively and uploads every file that passes the filters, as one model. You can filter files with shell-style wildcard patterns, such as *.bin:
  • Allow patterns: if set, only files that match at least one pattern are scanned.
  • Ignore patterns: files that match any pattern are skipped.
How patterns are matched differs by language:
allow_file_patterns and ignore_file_patterns use fnmatch against each file’s path, and * also matches /. The SDK always adds these ignore patterns to yours: *.txt, *.md, *.lock, .gitattributes, and anything under .git. If HiddenLayer rejects a file as a duplicate within the same scan, the SDK logs a warning and skips that file instead of failing the whole scan.
Expected result: one report that covers every uploaded file, with an entry for each file in file_results.

Scan a Hugging Face model

Scan a model repository on Hugging Face. The examples scan prajjwal1/bert-tiny, a small public BERT model. For a private or gated repository, provide a Hugging Face access token.
scan_huggingface_model downloads the repository with huggingface_hub, then scans the downloaded folder.Extra prerequisite: pip install huggingface_hub.A public repository needs no token. For a private or gated one, pass hf_token a token string, or True to read the token saved in your local Hugging Face configuration (for example, after you log in with hf auth login). With True and no saved token, huggingface_hub raises LocalTokenNotFoundError. The example reads the token from an HF_TOKEN environment variable that you set yourself, and sends none when it isn’t set.
Python
If you omit model_name, the SDK uses repo_id as the model name. The revision (a branch, tag, or commit hash) is also used as the model version, which is "1" when you omit it. Other options are local_dir (download location), ignore_file_patterns, and force_download.
Expected result: a report for the downloaded repository with inventory.origin set to Hugging Face.

Scan a model in AWS S3

Scan a single model file stored in S3.
scan_s3_model downloads the file with boto3, then scans it.Extra prerequisite: pip install boto3.By default the SDK creates boto3.client("s3"), which uses the standard AWS credential chain. That chain checks sources such as the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, your AWS config files, and attached IAM roles. Pass your own client with s3_client if you need a specific profile or region.
Python
Expected result: a report with inventory.origin set to S3.

Scan a model in Azure Blob Storage

Scan a single blob in Azure Blob Storage.
scan_azure_blob_model downloads the blob with the Azure Storage SDK, then scans it.Extra prerequisite: pip install azure-identity azure-storage-blob.By default the SDK authenticates with DefaultAzureCredential, which tries several Azure sign-in methods, such as environment variables, managed identity, and the Azure CLI. To use a shared access signature (SAS) token instead, pass it as credential. Read it from an environment variable rather than writing it in your code.
Expected result: a report with inventory.origin set to Azure Blob Storage.

Temporary files for downloaded models

The S3 and Azure helpers always download to /tmp/<file name>. The Hugging Face helper downloads to /tmp/<repo_id> unless you set local_dir. Keep these points in mind:
  • The SDK does not delete downloaded files after the scan. Remove them yourself if disk space or data retention matters.
  • Because the paths are fixed under /tmp, the S3 and Azure helpers may not work on Windows. On Windows, download the file yourself and call scan_file, or set local_dir for Hugging Face.

Scan a remote model with the community scanner

Use the community scanner when HiddenLayer can reach the model directly, for example through a presigned URL or a public Hugging Face repository. HiddenLayer fetches the model itself, so nothing is downloaded to or uploaded from your machine. Set the model source to one of the CommunityScanSource constants. They have the same names in every SDK: import CommunityScanSource from hiddenlayer.lib in Python, from @hiddenlayerai/hiddenlayer-sdk in TypeScript, and from com.hiddenlayer.api.lib in Java.
This page does not cover the access setup each source type requires on the HiddenLayer side (for example, which IAM role HiddenLayer assumes). The HUGGING_FACE example below follows the SDKs’ own usage.
The model version defaults to "main". Expected result: a report for the remote model. The repository in this example is intentionally vulnerable, so expect detections.

Start a scan without waiting

By default, scan methods block until the scan finishes. Turn off waiting to return as soon as the scan starts. This is useful in web services or pipelines where you do not want to hold a process open. When you don’t wait:
  • For upload-based scans, the upload itself still finishes before the method returns. Only the wait for the analysis is skipped.
  • The returned report is a point-in-time snapshot. Its status is often pending or running, and file_results may be incomplete.
  • Save the report’s scan ID, then fetch an updated report later: scan_result(scan_id=...) on client.model_scanner or client.community_scanner in Python, getScanResults(client, scanId) in TypeScript, or ScanUtils.getScanResults(client, scanId) in Java.
If the new scan is not visible yet, the SDK retries up to five times. If the scan still cannot be found, Python raises hiddenlayer.NotFoundError, TypeScript throws a HiddenLayerError with statusCode 404, and Java throws a HiddenLayerApiException with statusCode() 404.

Wait with a time limit

When the SDK waits for results, it polls the scan status with exponential backoff (up to 30 seconds between checks) until the scan is done, failed, or canceled. There is no overall timeout. If a scan stays in pending or running, your program waits indefinitely. In CI/CD or other unattended environments, start the scan without waiting and poll yourself with a deadline. The scan summary endpoint (scans.results.retrieve_summary in Python, scans.results.retrieveSummary in TypeScript, scans().results().retrieveSummary in Java) is a lightweight call that returns the status and summary without the per-file results.
Expected result: the program either prints the final status and highest threat level, or exits with a timeout message that includes the scan ID so you can check it later. For lower-level scan APIs, such as listing scan jobs, paging through file results, and downloading results in SARIF format (Static Analysis Results Interchange Format, a JSON format that many code-scanning tools accept), see API usage examples.

Common errors and fixes

The download helper you called needs a package that the SDK does not install. In Python the error is an ImportError such as Python package boto3 is not installed. In TypeScript it is an Error such as This scan needs @aws-sdk/client-s3: install it beside @hiddenlayerai/hiddenlayer-sdk. Install the package listed in Before you begin.
HiddenLayer rejected your credentials. Check that HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET are set in the same shell or process that runs your program. Also check that the client’s environment matches your account’s region (prod-us or prod-eu). See Authentication and configuration.
Your credentials are valid but lack access to model scanning. Ask a Console administrator to check the client credential’s permissions.
In Python (RuntimeError) and TypeScript (Error), the S3 or Azure download failed before the scan started. The message includes the underlying error. Check the bucket, key, container, and blob names, and confirm that your AWS or Azure credentials can read the object.
Paths are resolved relative to the current working directory. Use an absolute path, or run the program from the expected directory. Python raises FileNotFoundError, TypeScript throws an error with code ENOENT, and Java throws an IllegalArgumentException such as File does not exist: ....
Failed scans are returned, not raised. Inspect file_error on each entry in file_results for scanner error messages, and check summary.files_failed_to_scan.
Waiting for results has no overall timeout. Use the pattern in Wait with a time limit.
Without waiting, the SDK retries a few times while a new scan becomes available. If it still fails with a 404, wait briefly and fetch the results again. Also confirm you are using the same environment (region) that started the scan.
For more on exceptions and retries, see Error handling and Troubleshooting.